我是编程新手,需要一些帮助。我有一个包含很多名称和爱好的文本文件,看起来像这样:
Jack:crafting
彼得:徒步旅行
Wendy:gaming
莫妮卡:网球
Chris:origami
苏菲:体育
Monica:design
重复了一些名字和爱好。我正在尝试使程序显示如下内容:
Jack:手工艺,电影,瑜伽
温迪:游戏,远足,运动
到目前为止,这是我的程序,但末尾的4行是错误的。
return Response.ok(makePDF.makePDFEjecutivo(idalle)).header("Content-Disposition", "inline; filename=" + pdfName + ".pdf").build();
答案 0 :(得分:1)
您可以尝试类似的方法。在我试图向您展示如何以更“ 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概念的方向。如果您还没有完成入门教程,我肯定会推荐它。
答案 1 :(得分:1)
在这种情况下,我将使用defaultdict。
import sys
from collections import defaultdict
def create_dictionary(inputfile):
d = defaultdict(list)
for line in inputfile:
name, hobby = line.split(':', 1)
d[name].append(hobby.strip())
return d
with open(sys.argv[1]) as fp:
for name, hobbies in create_dictionary(fp).items():
print(name, ': ', sep='', end='')
print(*hobbies, sep=', ')
您的示例给了我这个结果:
Sophie: sport
Chris: origami
Peter: hiking
Jack: crafting
Wendy: gaming
Monica: tennis, design
答案 2 :(得分:1)
您可以尝试这个
data = map(lambda x:x.strip(), open('hobbies_database.txt'))
tmp = {}
for i in data:
k,v = i.strip().split(':')
if not tmp.get(k, []):
tmp[k] = []
tmp[k].append(v)
for k,v in tmp.iteritems():
print k, ':', ','.join(v)
输出:
Monica : tennis,design
Jack : crafting
Wendy : gaming
Chris : origami
Sophie : sport
Peter : hiking