python - 在 Python 中将文件解析为特定内容
问题描述
我有一个包含名称和数字的文件。
前任:
25
27
90
Robert
34
Liam
我想要做的是在名称前添加所有数字并将它们与分配给它们的名称一起存储。我想让它有点像元组列表。例如,对于名称 Robert,您应该得到 (142, Robert)。有什么建议吗?
解决方案
我会编辑您的问题,以便更好地向我解释您的输入数据,但我能够通过以下方式获得您的预期输出:
文件.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')]
推荐阅读
- c# - WPF - OnDrop 事件块拖放到模型对话框中
- node.js - 发现 RegExp 构造函数的非文字参数 - Eslint 问题
- java - 带有额外列和复合键的@ManyToMany注释spring boot JPA,插入错误
- python - 使用 pytest 夹具创建目录
- vue.js - 在 Vuetify 中制作响应式卡片网格
- android - Xamarin Android 应用程序未使用 BlackBerry UEM 调用 SOAP Web 服务
- asp.net - 您能否使用 Visual Studio Web 发布到 Azure Web App 部署单个 aspx.cs 文件(Azure 运行时问题)
- python - 比较 2 个数据框,找到匹配的行,然后对一列求和
- azure - 使用 Azure DevOps (AWS ToolKit) 将文件从 s3 下载到 ec2 实例
- android - 应用程序描述未在 Play 商店中更新