0

プログラミングは初めてで、来週試験があります。私たちはコースで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 に答える