【问题标题】:Python File manipulation of a list of names名称列表的 Python 文件操作
【发布时间】:2019-03-13 02:18:34
【问题描述】:

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

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

将名字分成名字和姓氏

将其存储到字典中

将字典添加到列表中

按照上面的语句,你会得到一个如图所示的名字列表

[ {‘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)

【问题讨论】:

  • 并且source.txt中预计会有空行?

标签: python


【解决方案1】:

您无需使用额外的数据结构即可轻松完成一次操作(免责声明:未经测试):

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

【讨论】:

  • 请注意write 方法不接受多个参数,并且它不输出尾随换行符。
【解决方案2】:

您可以将列表推导与 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'}]

【讨论】:

    【解决方案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')
    

    【讨论】:

    • 也许用', '.join(line.rstrip..)替换''.join(line.rstrip..)
    • partition 不是这样工作的。 partition 方法的结果列表已经包含分隔符。
    • 不错。不知道那件事。 :(
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多