名称列表的Python文件操作

2024-06-26 14:18:59 发布

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

我有一个文件,上面有一个名字列表,按姓氏、名排列。我想实现创建另一个文件,但组织它的名字,姓氏

使用以下提示: 迭代每一行,然后

把名字分成名字和姓氏

把它存到字典里

将词典添加到列表中

在遵循上述语句之后,您将得到一个名称列表,如图所示

[{'fname':'Jeanna','lname':'Mazzella'},{'fname':'Liane','lname': '斯帕塔罗'},…]

source.txt = 

Mazzella, Jeanna

Spataro, Liane

Beitz, Sacha

Speegle, Pura

Allshouse, Parker

到目前为止,我试图把这些名字分为名字和姓氏。我陷入了把输出作为提示的部分。有人能帮忙吗

f = open('source.txt')
namlist = f.read()
split = namlist.split()

fname = split[1:5:2] #This gets the first names
print(fname)
for i in fname:
  print(i)

lname = split[0:5:2] #This gets the last names
for j in lname:
  print(j)

Tags: 文件txtsource列表this名字fnamesplit
3条回答

如果您的目标是简单地交换源文件中的名字和姓氏,那么可以使用str.partition方法用', '对行进行分区,反转生成的列表并将它们连接回字符串:

with open('source.txt') as f, open('updated.txt', 'w') as output:
    output.write('\n'.join(''.join(line.rstrip().partition(', ')[::-1]) for line in f) + '\n')

可以将列表理解与dict构造函数结合使用,该构造函数从文件中按', '拆分的行中获取压缩的键和值:

[dict(zip(('lname', 'fname'), line.rstrip().split(', '))) for line in f]

根据您的示例输入,返回:

[{'lname': 'Mazzella', 'fname': 'Jeanna'}, {'lname': 'Spataro', 'fname': 'Liane'}, {'lname': 'Beitz', 'fname': 'Sacha'}, {'lname': 'Speegle', 'fname': 'Pura'}, {'lname': 'Allshouse', 'fname': 'Parker'}]

您可以轻松地一次完成,而无需使用其他数据结构(免责声明:未经测试):

with open('source.txt') as fin, open('destination.txt', 'w') as fout:
    for line in fin:
        lastname, firstname = line.strip().split(', ')
        fout.write(f'{firstname}, {lastname}\n')

相关问题 更多 >