Sum of strings extracted from text file using regex

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

    My first attempt to answer with the use of regular expressions, I find it a great skill to practise, that reading other's code.

    import re # import regular expressions
    chuck_text = open("regex_sum_286723.txt")
    numbers = []
    Total = 0
    for line in chuck_text:
        nmbrs = re.findall('[0-9]+', line)
        numbers = numbers + nmbrs 
    for n in numbers:
        Total = Total + float(n)
    print "Total = ", Total 
    

    and thanx to Beer for the 'comprehension list' one liner, though his 'r' seems not needed, not sure what it does. But it reads beautifully, I get more confused reading two lots of loops like my answer

    import re
    print sum([int(i) for i in re.findall('[0-9]+',open("regex_sum_286723.txt").read())])
    
    0 讨论(0)
  • 2020-12-10 20:40
    import re
    print sum([int(i) for i in re.findall('[0-9]+',open(raw_input('What is the file you want to analyze?\n'),'r').read())])
    

    You can compact it into one line, but this is only for fun!

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