首页 > 解决方案 > 在 Python 中将文件解析为特定内容

问题描述

我有一个包含名称和数字的文件。

前任:

25
27
90
Robert
34
Liam

我想要做的是在名称前添加所有数字并将它们与分配给它们的名称一起存储。我想让它有点像元组列表。例如,对于名称 Robert,您应该得到 (142, Robert)。有什么建议吗?

标签: pythonfiletuples

解决方案


我会编辑您的问题,以便更好地向我解释您的输入数据,但我能够通过以下方式获得您的预期输出:

文件.txt

25
27
90
Robert
34
Liam

主文件

with open('/path/to/some/file.txt', 'r') as f:
    lines = [line.strip() for line in f.read().split()]

res = []
tot = 0
for line in lines:
    if line.isdecimal():
        tot += int(line)
    else:
        res.append((tot, line))
        tot = 0

print(res)

输出:

[(142, 'Robert'), (34, 'Liam')]

推荐阅读