0

Google トレンドから次の形式でデータを表示する CSV ファイルをダウンロードしました。

Top cities for golden globes
City,golden globes
New York (United States),100
Los Angeles (United States),91
Toronto (Canada),69

Top regions for golden globes
Region,golden globes
United States,100
Canada,91
Ireland,72
Australia,72

空白で区切られたこれらのグループが 3 ~ 4 あります。各グループの最初の行には、キーとして使用するテキストが含まれており、その後にそのキーに関連付ける必要がある辞書のリストが続きます。これを実現するために使用できる Python ツールについて何かアドバイスはありますか? 私は Python の CSV ライブラリがうまくいきません。

上記の CSV からの望ましい出力は次のようになります。

{
"Top cities for golden globes" :
   {
      "New York (United States)" : 100,
      "Los Angeles (United States)" : 91,
      "Toronto (Canada)" : 69
   },
"Top regions for golden globes" :
   {
      "United States" : 100,
      "Canada" : 91,
      "Ireland" : 72,
      "Australia" : 72
   }
}
4

2 に答える 2

0

あなたの入力形式は非常に期待できるので、CSV ライブラリなしで手動で行います。

import json
from collections import defaultdict

fh = open("yourfile.csv")
result = defaultdict(dict) #dictionary holding the data
current_key = "" #current category
ignore_next = False #flag to skip header

for line in fh:
    line = line.strip() #throw away newline
    if line == "": #line is empty
        current_key = ""
        continue
    if current_key == "": #current_key is empty
        current_key = line #so the current line is the header for the following data
        ignore_next = True
        continue
    if ignore_next: #we're in a line that can be ignored
        ignore_next = False
        continue
    (a,b) = line.split(",")
    result[current_key][a] = b
fh.close()

#pretty-print data
print json.dumps(result, sort_keys=True, indent=4)
于 2015-01-14T00:28:38.170 に答える