简体   繁体   English

1线正则表达式可汇总txt文件中的数字

[英]1-liner regex to sum up numbers in a txt file

Just started learning python and wonder how does one sum up all the numbers in a txt file with regex and list compression. 刚开始学习python,想知道如何用正则表达式和列表压缩将txt文件中的所有数字相加。

I wrote the following but not sure how to avoid adding up numbers from empty lists in the findall search: 我写了以下内容,但不确定如何避免在findall搜索中将空列表中的数字相加:

import re

print (sum([int(num[0]) for num[0] in re.findall('[0-9]+', open('xxx.txt').read().split())]))

You don't need to split the input data since re.findall should work on fileobj.read() . 您不需要拆分输入数据,因为re.findall应该适用于fileobj.read() And also don't specify the index on the intermediate variable while iterating over the resultant list of re.findall . 并且在迭代re.findall的结果列表时,也不要在中间变量上指定索引。

print (sum(int(num) for num in re.findall('[0-9]+', open('xxx.txt').read())))

With \\d+ you will not have empty strings. 使用\\d+您将没有空字符串。 With map you will convert all your strings to integer and then sum them up with sum(). 使用map时,您会将所有字符串转换为整数,然后使用sum()求和。

print(sum(map(int, re.findall('\d+', open('xxx.txt').read()))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM