python - 解析文本文件不同行的有效方法
问题描述
我有一个包含如下数据的文本文件:
1 --- 1 --- 100
2 --- 1 --- 200
3 --- 1 --- 100
1 --- 2 --- 300
2 --- 2 --- 100
3 --- 2 --- 400
我想提取对应于第二列不同值的第三列数据,例如在第三列中添加三个数字,对应于第二列中的数字 1,依此类推。我可以逐行遍历文本,然后在每行中找到第三列并添加它们。但这不是我想要的。我应该如何在 Python 中有效地做到这一点?
解决方案
使用itertools.groupby()
.
例如,我正在使用您的确切“数据结构”(stackoverflow 问题中的一堆文本):
import itertools
data_structure = '''
1 --- 1 --- 100
2 --- 1 --- 200
3 --- 1 --- 100
1 --- 2 --- 300
2 --- 2 --- 100
3 --- 2 --- 400
'''.splitlines()
# create a key function able to extract the data you want to group:
def _key(line):
return line.strip().split(' --- ')[1] # the 1 here means second column
#cleanup data:
clean_data = (line.strip() for line in data_structure if line.strip())
# then pass it to itertools.groupby:
for key, lines in itertools.groupby(clean_data, key=_key):
print("Lines that contain number", key, 'in second column:')
print(', '.join(lines))
结果:
Lines that contain number 1 in second column:
1 --- 1 --- 100, 2 --- 1 --- 200, 3 --- 1 --- 100
Lines that contain number 2 in second column:
1 --- 2 --- 300, 2 --- 2 --- 100, 3 --- 2 --- 400
编辑:既然您编辑了问题,并说您有一个文本文件,那么您可以使用它来代替data_structure
它,它将起作用:
data_structure = open('myfile.txt')
其余代码保持不变
推荐阅读
- python-3.x - Python子文件夹模块无法导入其他子文件夹模块
- python - 如何使用 Python 将 sudoers 文件转换为 JSON 数据?
- javascript - 单击单行突出显示时的反应表。禁用多选
- c# - “当前上下文中不存在占位符”
- botframework - Microsoft/BotFramework-WebChat 是否具有 Sneak Peek 功能?
- linux - 在 Linux 中将输入/传递文本文件 example.txt 发送到 Install.sh
- game-engine - Godot 3.1 - 动态加载资源
- r - R中变量名称的正则表达式(重新格式化数据集)
- go - 无法识别的导入路径“syscall/js”
- python - 使用单元格创建地图的 Python 函数