尝试比较文本文件中的多行并通过合并它们进行打印

2024-09-30 18:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python比较多行并基于第一个单词连接相同的行 我是python的初学者,尝试比较文本文件中的多行,并通过连接它们来打印

文本文件

Rolt12 is a musician
Rolt1 is dancer
Rolt1 is an actor
Rolt14 is a singer

我正在打印

Rolt12 is a musician
Rolt1 is a dancer; is an actor
Rolt14 is a singer

到目前为止,我知道文件的打开和写入

with open ('input.txt','r') as ifh, with open ('out.txt', 'w') as ofh:
    ifh.readlines()

在此之后,我想我应该比较文本文件中的行,检查第一行是否相同。之后,如果第一个单词相同,则将它们连接起来。但我不知道如何比较和加入他们。任何帮助都将不胜感激……谢谢


Tags: txtansingerisaswithopen单词
2条回答

解决这个问题的合理方法是使用字典来存储每个名字的职业列表。例如,如果您有以下设置:

data = [("Rolt12", "musician"), ("Rolt1", "dancer"), ("Rolt1", "actor"), ("Rolt14", "singer")]

您可以使用以下代码为每个姓名创建职业列表:

occupations = {}
for name, occupation in data:
    if name not in occupations:
        occupations[name] = []
    occupations[name].append(occupation)

或者,更习惯地说:

import collections
occupations = collections.defaultdict(list)
for name, occupation in data:
    occupations[name].append(occupation)

然后,您可以迭代字典以打印所需的数据:

for name, all_occupations in occupations.items():
    occupations_string = "; ".join(all_occupations)
    print(f"{name} is a {occupations_string}")

您可以使用字典将每一行拆分为两部分,一部分是“name”,另一部分是(行的其余部分没有名称)。使用名称作为字典中的键

from collections import defaultdict
with open('data.txt') as fp:
    d = defaultdict(list)
    for line in fp:
        x = line.strip().split(' ', 1)
        d[x[0]].append(x[1])

#writing output to new file
with open('output.txt', 'w') as fw:
    for k, v in d.items():
        fw.write( k + ' ' + '; '.join(v) + '\n')

输出:

Rolt12 is a musician
Rolt1 is dancer; is an actor
Rolt14 is a singer

相关问题 更多 >