Sum of strings extracted from text file using regex

后端 未结 8 1144
梦毁少年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:20

    Here is my solution to this problem.

    import re
    
    file = open('text_numbers.txt')
    sum = 0 
    
    for line in file:
        line = line.rstrip()
        line = re.findall('([0-9]+)', line)
        for i in line:
            i = int(i)
            sum += i    
    
    print(sum)
    

    The line elements in first for loop are the lists also and I used second for loop to convert its elements to integer from string so I can sum them.

提交回复
热议问题