Sum of strings extracted from text file using regex

后端 未结 8 1125
梦毁少年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:15
    import re
    text = open('text_numbers.txt')
    data=text.read()
    print sum(map(int,re.findall(r"\b\d+\b",data)))
    

    Use .read to get content in string format

    0 讨论(0)
  • 2020-12-10 20:15
    import re
    
    fl=open('regex_sum_7469.txt')
    ls=[]
    
    for x in fl: #create a list in the list
       x=x.rstrip()
       print x
       t= re.findall('[0-9]+',x) #all numbers
       for d in t: #for loop as there a empthy values in the list a
            ls.append(int(d))
    print (sum(ls))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-10 20:30

    I dont know much python but I can give a simple solution. Try this

    import re
    hand = open('text_numbers.txt')
    x=list()
    for line in hand:
        y=re.findall('[0-9]+',line)
        x=x+y
    sum=0
    for i in x:
        sum=sum + int(i)
    print sum
    
    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题