0

一連のレストランの詳細が次々に示されているテキスト ファイルがあります。詳細は、特定のレストランの名前、評価、価格、料理の種類です。テキストファイルの内容は以下の通りです。

George Porgie
87%
$$$
Canadian, Pub Food

Queen St. Cafe
82%
$
Malaysian, Thai

Dumpling R Us
71%
$
Chinese

Mexican Grill
85%
$$
Mexican

Deep Fried Everything
52%
$
Pub Food

以下のような一連の辞書を作成したいと思います。

Restaurant name to rating:
# dict of {str : int}
name_to_rating = {'George Porgie' : 87,
'Queen St. Cafe' : 82,
'Dumpling R Us' : 71,
'Mexican Grill' : 85,
'Deep Fried Everything' : 52}

Price to list of restaurant names:
# dict of {str : list of str }
price_to_names = {'$'   :  ['Queen St. Cafe', 'Dumpling R Us', 'Deep Fried Everything'],
'$$'  :  ['Mexican Grill'],
'$$$' :  ['George Porgie'], 
'$$$$' : [ ]}

Cuisine to list of restaurant name:
#dic of {str : list of str }
cuisine_to_names = {'Canadian' : ['George Porgie'],
'Pub Food' : ['George Porgie', 'Deep Fried Everything'],
'Malaysian' : ['Queen St. Cafe'],
'Thai' : ['Queen St. Cafe'],
'Chinese' : ['Dumpling R Us'],
'Mexican' : ['Mexican Grill']}

上記の辞書を作成するための Python での最良の方法は何ですか?

4

2 に答える 2

1

いくつかのコンテナーを初期化します。

name_to_rating = {}
price_to_names = collections.defaultdict(list)
cuisine_to_names = collections.defaultdict(list)

ファイルを一時文字列に読み込みます。

with open('/path/to/your/file.txt') as f:
  spam = f.read().strip()

構造が一貫している (つまり、2 つの改行で区切られた 4 行のチャンク) と仮定して、チャンクを反復処理し、コンテナーに入力します。

restraunts = [chunk.split('\n') for chunk in spam.split('\n\n')]
for name, rating, price, cuisines in restraunts:
  name_to_rating[name] = rating
  # etc ..
于 2013-03-26T05:05:44.987 に答える
0

メインの読み取りループでは、enumerate と modulo を使用して、行のデータが何であるかを知ることができます。

for lineNb, line in enumerate(data.splitlines()):
    print lineNb, lineNb%4, line

price_to_namesおよび辞書のcuisine_to_names場合、defaultdict を使用できます。

from collections import defaultdict
price_to_names = defaultdict(list)
于 2013-03-26T05:09:15.417 に答える