Sum of strings extracted from text file using regex

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

    import re
    sample = open ('text_numbers.txt')
    total =0
    dignum = 0 
    
    for line in sample:
        line = line.rstrip()
        dig= re.findall('[0-9]+', line)
    
        if len(dig) >0:
            dignum += len(dig)
            linetotal= sum(map(int, dig))
            total += linetotal
    
    print 'The number of digits are:  ' 
    print dignum
    print 'The sum is: '
    print total     
    print 'The sum ends with: '
    print  total % 1000
    

提交回复
热议问题