【问题标题】:How to extract string (numbers) from txt file and convert to integers using regular expressions in python如何从txt文件中提取字符串(数字)并在python中使用正则表达式转换为整数
【发布时间】:2019-11-07 10:32:17
【问题描述】:

通读并解析包含文本和数字的文件。提取文件中的所有数字并计算数字的总和。 txt file attached

这适用于 python 3 及更高版本。

import re
names=open("regex_sum_319771_actual.txt")
numlist = list()
for files in names:
    files = files.rstrip()
    ext =re.findall('([0-9]+)',files)
    if len(ext)!= 1 :
        continue
    num = int(ext[0])
    numlist.append(num)
print('done',sum(numlist))


#the sum should give me an output ending with 689

【问题讨论】:

    标签: python string int extract


    【解决方案1】:

    这将起作用:

    import re
    
    
    with open("regex_sum_319771_actual.txt", "r") as f:
        nums = re.findall(r'([0-9]+)', f.read())
        print(sum([int(i) for i in nums]))
    

    PS:如果不使用with语句,请不要忘记在阅读后关闭文件

    【讨论】:

    • 谢谢!这很有价值,如果您不介意,您能说出我的代码有什么问题吗?
    • 您需要将文件传递给正则表达式一次,然后您可以循环遍历您的正则表达式列表。如果分机有一个像['42'] 这样的匹配项,这个if len(ext)!= 1 将忽略,所以你最终只对包含多个数字的列表求和。你得到79135
    【解决方案2】:

    您可以逐个字符地迭代。

    import re
    names = open("regex_sum_319771_actual.txt", 'r')
    nbr = []
    for line in names:
        for carac in line:
           if re.match(r'\d', carac):
                nbr.append(int(carac))
    
    print(sum(nbr))
    names.close()
    

    【讨论】:

    • 这不是像 42 这样的数字的总和是 6 吗?
    • 对不起,总和(nbr)
    • 好吧,但是 OP 希望“42”和“16”之和为 58。您的解决方案将有 sum([4, 2, 1, 6]),即 13。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多