我的程序应该在名为mail.txt的文件中读取,如下所示:
Jane Fairfax,Letter
Frank Churchill,Letter
Emma Woodhouse,Letter
Frank Churchill,Letter
Harriet Smith,Package
Emma Woodhouse,Letter
Philip Elton,Package
Emma Woodhouse,Package
我的程序应该像这样工作:
Name: Emma Woodhouse
2 Letters
1 Package
这是我的代码:
q = input("Name: ")
p = open("mail.txt", "r")
name_list = p.readlines()
lista = {}
for i in name_list:
i = i[:-1]
name_list = i
我不知道接下来该怎么办。有什么建议吗?谢谢。
答案 0 :(得分:1)
你非常接近。您希望使用您创建的字典来跟踪您阅读的所有名称以及每个人收到的邮件类型。以下是我提出的建议:
tenants = {}
def print_mail(name):
if name in tenants:
print 'Name: {}'.format(name)
print '{} Letters'.format(tenants[name]['Letter'])
print '{} Packages'.format(tenants[name]['Package'])
else:
print 'Name not found'
def read_mail_file():
# Using the with statement creates a file object and
# automatically closes it for you when the statement exits
with open('mail.txt', 'r') as infile:
for line in infile.readlines():
# Convert the line into an array split by commas
line = line.strip().split(',')
name = line[0]
mail_type = line[1]
# If you have not already seen this person then
# create an embedded dictionary to keep track of their mail
if name not in tenants:
tenants[name] = {'Letter': 0, 'Package': 0}
# Then, just update the type of mail they received on this
# line
tenants[name][mail_type] += 1
if __name__ == "__main__":
read_mail_file()
print_mail('Emma Woodhouse')
答案 1 :(得分:0)
这是您的解决方案。
import collections
y=[]
with open('mail.txt') as infile:
counts = collections.Counter(l.strip() for l in infile)
for line, count in counts.most_common():
y.append(line + ',' + str(count))
line=input("Name: ")
for i in y:
if line == str(i).split(',')[0]:
print(str(i).split(',')[2] + ' ' + str(i).split(',')[1])
答案 2 :(得分:-1)
首先,我们可以使用列表推导来解析文件本身。
In [1]: with open("mail.txt") as file:
...: items = [item.split(',') for item in file.read().split('\n')[:-1]]
...:
In [2]: items
Out[2]:
[['Jane Fairfax', 'Letter'],
['Frank Churchill', 'Letter'],
['Emma Woodhouse', 'Letter'],
['Frank Churchill', 'Letter'],
['Harriet Smith', 'Package'],
['Emma Woodhouse', 'Letter'],
['Philip Elton', 'Package'],
['Emma Woodhouse', 'Package']]
然后我们可以使用另一个理解来确定属于特定人的项目。
In [3]: received = [kind for (name, kind) in items if name == recipient]
In [4]: received
Out[4]: ['Letter', 'Letter', 'Package']
然后,我们可以使用Counter
来计算收到的每件商品的数量。
In [5]: from collections import Counter
In [6]: Counter(received)
Out[6]: Counter({'Letter': 2, 'Package': 1})
In [7]: totals = dict(Counter(received))
In [8]: totals
Out[8]: {'Letter': 2, 'Package': 1}
最后,我们可以使用for
循环以所需的格式显示它。
In [9]: print("Name:", recipient)
...: for (item, count) in totals.items():
...: print(count, item)
...:
Name: Emma Woodhouse
2 Letter
1 Package