0

我是第一次做编程,下周要考试。我们在课程中使用 diong python (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
 '''

您所做的任何帮助/提示或解决方案都会非常有帮助。就像我不想要代码一样,我想知道它背后的想法。

当我读到这个问题时,我以为您正在拨打一个号码并想要该值或其他东西。我认为那是错误的

4

1 回答 1

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)'}
于 2013-07-25T23:24:05.080 回答