我第一次做节目,下周我有考试。我们在课程中是蟒蛇(Python 3)
我从过去的文件名考试中得到了这个问题的帮助。我几乎不了解如何调用它们的文件名。我知道文件的基本内容。在如何readline跳过一行。但没什么难的。
所以我有一个填充菜单的文件名,我想从中输入字典。我们只给出了这个例子。我不知道它喷出它或我必须做什么。
这是提供的示例
def read_menu(menu_file):
'''(file open for reading) -> dict of int to str
Read menu_file; each menu item in the restaurant has a number and a name.
The resulting dictionary maps numbers to names.
Sample input file:
1 Fried rice
2 Plain white rice
3 Plain brown rice
10 Chive dumpling (steamed)
11 Pork and shrimp dumpling (steamed)
12 Mushroom dumpling (steamed)
13 Pork and bitter melon dumpling (steamed)
14 Cherry dumpling (steamed)
20 Pork and shrimp dumpling (fried)
21 Pork dumpling (fried)
101 Bubble tea
102 Ice tea
'''
任何有关您所做的帮助/提示或解决方案都会非常有帮助。就像我不想要的代码一样,我想知道背后的想法。
当我读到这个问题时,我以为你在呼叫一个号码,并希望得到这个价值。而我认为这是错误的
答案 0 :(得分:0)
我想这可行。
def read_menu(menu_file):
d = dict()
with open(menu_file) as menu_text:
lines = menu_text.readlines()
for line in lines:
w = line.split()
try: d[int(w[0])] = ' '.join(w[1:])
except: pass
return d
在您的测试输入上:
>>> read_menu("menu.txt")
{1: 'Fried rice', 2: 'Plain white rice', 3: 'Plain brown rice', 101: 'Bubble tea
', 102: 'Ice tea', 10: 'Chive dumpling (steamed)', 11: 'Pork and shrimp dumpling
(steamed)', 12: 'Mushroom dumpling (steamed)', 13: 'Pork and bitter melon dumpl
ing (steamed)', 14: 'Cherry dumpling (steamed)', 20: 'Pork and shrimp dumpling (
fried)', 21: 'Pork dumpling (fried)'}