名称列表的 Python 文件操作

标签 python

我有一个文件,其中包含按姓氏、名字组织的名称列表。我想实现创建另一个文件,但将其组织为 first name , last name。

使用这些提示: 遍历每一行,然后

将名字分成名字和姓氏

将其存储到字典中

将字典追加到列表中

完成上述语句后,您将得到如图所示的名称列表

[ {'fname': 'Jeanna' , 'lname': 'Mazzella'}, {'fname': 'Liane' , 'lname': ‘Spataro’}, …….. ]

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)

最佳答案

您可以在不使用额外数据结构的情况下一次轻松完成(免责声明:未经测试):

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')

关于名称列表的 Python 文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127882/

相关文章:

python - 提高SQLAlchemy更新效率

python - 在 Python 中单独测试正无穷大或负无穷大

python - 使用 tensorflow 删除图像的最后一行和最后一列

python - 删除滚动条以显示完整表格

python - 在 django 模板中使用 if else 的正确方法?

python - python函数中的奇怪返回值

python - 使用 pandas 根据特定列中的条件替换日期值

Python处理日期和时间

python - Pandas :计算两列的不同组合并添加到同一数据框

python - Kafka python API 是否支持流处理?