首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Python将特定的CSV格式转换为JSON

如何使用Python将特定的CSV格式转换为JSON
EN

Stack Overflow用户
提问于 2015-01-14 00:20:43
回答 2查看 245关注 0票数 0

我已从谷歌趋势下载了一个CSV文件,该文件以这种格式显示数据:

代码语言:javascript
复制
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的期望输出如下所示:

代码语言:javascript
复制
{
"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
   }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-14 00:28:38

您的输入格式是如此预期,我会手工完成,没有CSV库。

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2015-01-14 00:48:23

我会尝试这样的.

代码语言:javascript
复制
row = []
dd = {}
with open('the.csv') as f:
    r = csv.reader(f)
    while True:
        if row:  # normal case, non-empty row
            d[row[0]] = row[1]
            row = next(r, None)
            if row is None: break
        else:  # row is empty at start and after blank line
            category = next(f, None)
            if category is None: break
            category = category.strip()
            next(r)  # skip headers row
            d = dd[category] = {}
            row = next(r, None)
            if row is None: break

现在,dd应该是你想要的小块,你可以随意地使用它.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27933914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档