Sum of strings extracted from text file using regex

后端 未结 8 1140
梦毁少年i
梦毁少年i 2020-12-10 19:47

I am just learning python and need some help for my class assignment.

I have a file with text and numbers in it. Some lines have from one to three numbers and other

8条回答
  •  佛祖请我去吃肉
    2020-12-10 20:37

    import re
    import np
    text = open('text_numbers.txt')
    final = []
    for line in text:
        line = line.strip()
        y = re.findall('([0-9]+)',line)
    
        if len(y) > 0:
             lineVal = sum(map(int, y))
             final.append(lineVal)
             print "line sum = {0}".format(lineVal)
     print "Final sum = {0}".format(np.sum(final))
    

    Is that what you're looking for?

提交回复
热议问题