python - 如何将文本文件 (name1:hobby1 name2:hobby2) 制作成这个 (name1:hobby1, hobby2 name2:hobby1, hobby2)?
问题描述
我是编程新手,需要一些帮助。我有一个包含很多名字和爱好的文本文件,看起来像这样:
杰克:手工艺
彼得:远足
温迪:游戏
莫妮卡:网球
克里斯:折纸
苏菲:运动
莫妮卡:设计
有些名字和爱好是重复的。我试图让程序显示如下:
杰克:手工艺、电影、瑜伽
温迪:游戏、远足、运动
到目前为止,这是我的程序,但最后的 4 行不正确。
def create_dictionary(file):
newlist = []
dict = {}
file = open("hobbies_database.txt", "r")
hobbies = file.readlines()
for rows in hobbies:
rows1 = rows.split(":")
k = rows1[0] # nimi
v = (rows1[1]).rstrip("\n") # hobi
dict = {k: v}
for k, v in dict.items():
if v in dict[k]:
解决方案
你可以试试这样的。我特意重写了这篇文章,因为我试图向你展示如何以更“Pythonic 的方式”来解决这个问题。至少更多地使用该语言。
例如,您可以在字典中创建数组以更直观地表示数据。这样就可以更轻松地以您想要的方式打印信息。
def create_dictionary(file):
names = {} # create the dictionary to store your data
# using with statement ensures the file is closed properly
# even if there is an error thrown
with open("hobbies_database.txt", "r") as file:
# This reads the file one line at a time
# using readlines() loads the whole file into memory in one go
# This is far better for large data files that wont fit into memory
for row in file:
# strip() removes end of line characters and trailing white space
# split returns an array [] which can be unpacked direct to single variables
name, hobby = row.strip().split(":")
# this checks to see if 'name' has been seen before
# is there already an entry in the dictionary
if name not in names:
# if not, assign an empty array to the dictionary key 'name'
names[name] = []
# this adds the hobby seen in this line to the array
names[name].append(hobby)
# This iterates through all the keys in the dictionary
for name in names:
# using the string format function you can build up
# the output string and print it to the screen
# ",".join(array) will join all the elements of the array
# into a single string and place a comma between each
# set(array) creates a "list/array" of unique objects
# this means that if a hobby is added twice you will only see it once in the set
# names[name] is the list [] of hobby strings for that 'name'
print("{0}: {1}\n".format(name, ", ".join(set(names[name]))))
希望这会有所帮助,并可能为您指明更多 Python 概念的方向。如果您还没有通过介绍性教程...我肯定会推荐它。
推荐阅读
- join - PySpark 广播连接,其中左表比右表更小以适合内存
- flutter - Flutter:在关闭控制器上处理 HTTP 请求
- c - 一个字符串在一个点正确而在另一个点错误地打印它的内容,没有变化
- c# - 你如何在 C# 中制作向玩家射击的光线投射?
- c# - 在 XNA 中加载纹理的最快方法是什么
- javascript - 根据文本获取 div 元素
- go - 如何在切片中搜索元素并将其与变量进行比较
- r - 有没有办法使用 read.fortran() 来读取字符串而不是文件?
- python - 如何在我的代码中解决以下问题?
- linux - Linux 系统上 Azure Log Analytics 代理的代理设置