额外" u"在python中从json转换为csv时

时间:2015-12-08 17:23:24

标签: python json csv pandas

我尝试将json转换为csv,但还有额外的字母" u"已经出现在列表中的每个单词之前,我用pandas来读取这个csv数据, 这是我的代码:

import json
import csv
with open("train.json") as file:
    data = json.load(file)
with open("trainc.csv", "w") as file:
    csv_file = csv.writer(file)
    csv_file.writerow(data[0].keys())
    for item in data:
    csv_file.writerow(item.values())
import pandas as pd
train = pd.read_csv("trainc.csv", header=0)

作为json文件的示例,这是第一个:

{
    "id": 10259,
    "cuisine": "greek",
    "ingredients": [
      "romaine lettuce",
      "black olives",
      "grape tomatoes",
      "garlic",
      "pepper",
      "purple onion",
      "seasoning",
      "garbanzo beans",
      "feta cheese crumbles"
    ]
  }

我用这条线打印成分

print train['ingredients'][0] 

当我打印相同的记录时,输出就像那样:

[u'romaine lettuce', u'black olives', u'grape tomatoes', u'garlic', u'pepper', u'purple onion', u'seasoning', u'garbanzo beans', u'feta cheese crumbles']

1 个答案:

答案 0 :(得分:3)

u不在您的字符串中。它只是说数据的类型是unicode

for x in train['ingredients'][0]:
     print x

您发现数据中没有额外的u

Python str vs unicode types
http://www.diveintopython.net/xml_processing/unicode.html