gpt4 book ai didi

python - 从带有冒号的行中解析单词(简单的初学者作业)

转载 作者:行者123 更新时间:2023-12-01 00:11:24 25 4
gpt4 key购买 nike

使用“travel_plans.txt”中存储的数据创建一个名为“目的地”的列表。列表的每个元素都应包含文件中的一行,其中列出了一个国家/地区以及该国家/地区内的城市。

“travel_plans.txt”包含:

This summer I will be travelling.
I will go to...
Italy: Rome
Greece: Athens
England: London, Manchester
France: Paris, Nice, Lyon
Spain: Madrid, Barcelona, Granada
Austria: Vienna
I will probably not even want to come back!
However, I wonder how I will get by with all the different languages.
I only know English!

到目前为止,我已经编写了以下内容:

with open("travel_plans.txt","r") as fileref:
for line in fileref:
row = line.strip().split()
if ":" in row[0]:
destination = row
print(destination)

是否有更好的方法来获得相同的输出?

最佳答案

destination = []
with open("travel_plans.txt","r") as fileref:
for line in fileref:
row = line.strip()
if ":" in row:
destination.append(row)
print(destination)

对于一个小文件,超过这个值可能就有点过分了。

你可以让它变得更短。

destination = [line.strip() for line in fileref if ":" in line]
print(destination)

关于python - 从带有冒号的行中解析单词(简单的初学者作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59609972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com