Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 1行正则表达式,用于在txt文件中汇总数字_Python_Regex - Fatal编程技术网

Python 1行正则表达式,用于在txt文件中汇总数字

Python 1行正则表达式,用于在txt文件中汇总数字,python,regex,Python,Regex,刚开始学习python,想知道如何使用正则表达式和列表压缩将txt文件中的所有数字相加 我写了以下内容,但不确定如何避免在findall搜索中从空列表中添加数字: import re print (sum([int(num[0]) for num[0] in re.findall('[0-9]+', open('xxx.txt').read().split())])) 您不需要分割输入数据,因为re.findall应该在fileobj.read()上工作。并且在遍历re.findall的结果

刚开始学习python,想知道如何使用正则表达式和列表压缩将txt文件中的所有数字相加

我写了以下内容,但不确定如何避免在findall搜索中从空列表中添加数字:

import re

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

您不需要分割输入数据,因为
re.findall
应该在
fileobj.read()上工作。并且在遍历
re.findall
的结果列表时,也不要指定中间变量的索引

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

使用
\d+
将不会有空字符串。使用map,您将把所有字符串转换为整数,然后用sum()求和


尝试了以下操作,但似乎也不起作用:print(在re.findall('[0-9]+',open('regex_sum_256911.txt')。read().split())]中len[num]!=0的sum([int(num[0]))可以是负数还是浮点数?如果是,你需要一个更复杂的正则表达式模式。先生,你太棒了!如果这个答案对你有帮助,请接受它!
print(sum(map(int, re.findall('\d+', open('xxx.txt').read()))))