python - 使用 Python 正则表达式对整个文本中随机放置的整数求和

标签 python regex python-3.x

所以我有一个文本文件,其中有一些行,如下所示:

“这是 10 条左右 4 条通用文本。

4 内容并不重要 5 它说什么 1

我只是用它,

让 2 成为 2 点。”

我正在尝试使用 re.findall 查找分散在文本中的数字的总和。到目前为止我已经:

import re

handle=open('.txt')

for line in handle:

    num = re.findall('[0-9]+', line)
    if len(num)>0:
           num = list(map(int, num))
           total = sum(num)

这就是我所能得到的。使用 re.findall 为 num 分配一系列字符串整数列表 (['10', '4'], ['4', '5', '1'], [], ['2', '2'] )。 Len 过滤掉不包含数字的行(['10', '4'], ['4', '5', '1'], ['2', '2'])。 List(map()) 将列表从字符串转换为整数 ([10, 4], [4, 5, 1], [2, 2]),并将 sum(num) 分配给每个列表的总和 ([14] ,[10],[4])。从这里我试图将这三个数字相加。我想我正在寻找的是 sum(total(sum(num))) 但 Python 不喜欢这样。任何帮助将不胜感激。

最佳答案

您不必在每一行都应用正则表达式:

In [1]: import re

In [2]: txt = """This is 10 some 4 generic text.
   ...:    ...:
   ...:    ...: It doesn't 4 matter 5 what it says 1
   ...:    ...:
   ...:    ...: I'm just using it,
   ...:    ...:
   ...:    ...: To make 2 a 2 point."""

In [3]: sum(map(int, re.findall(r"\d+", txt)))
Out[3]: 28

因此对于文本文件,这应该有效:

import re

with open("input.txt", "r") as handle:
    print(sum(map(int, re.findall(r"\d+", handle.read()))))

关于python - 使用 Python 正则表达式对整个文本中随机放置的整数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015798/

相关文章:

python - 下载 PDF 作为文件对象,无需使用 Python 中的 Chrome 和 Selenium 下载文件

python - 将字典值求和到阈值 - itertools.takewhile?

python - 使用 Python 导入 - 将多个 excel 文件导入到数据框中

java - 正则表达式中的奇怪行为

JavaScript 验证问题

python - python中的标准随机选择

ruby - 提取带和不带终止字符的文件名

python-3.x - macOS Monterey - 安装 Scipy 错误 "No lapack/blas resources found"

Python 获取 Base64 编码的字节字符串作为字节串

python - 如何根据文件中的单词创建两个不同的列表?