【问题标题】:Extra "u" when converting from json to csv in python [duplicate]在python中从json转换为csv时额外的“u”[重复]
【发布时间】:2016-03-13 17:50:09
【问题描述】:

我尝试从 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']

【问题讨论】:

    标签: python json csv pandas


    【解决方案1】:

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

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

    您发现您的数据中没有多余的u

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

    【讨论】:

    • 但是当我尝试处理(成分)时,它作为字符串的一部分进入处理!我应该怎么做才能防止这种情况发生? @sudomakeinstall2
    • 不打印列表,打印列表内的字符串
    • 你为什么要阻止这种情况?有什么问题?
    • @sudomakeinstall2 我用了你的代码,没有你它也能正常工作:))。
    • @iayork 我使用 print 作为我的过程的指示
    猜你喜欢
    • 2022-08-03
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2018-06-06
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多