适用于Python 3的Json2csv转换器

时间:2018-07-31 03:43:42

标签: python json csv yelp

我正在使用Json2csv代码将Yelp数据集转换为csv文件(在此处提供:https://github.com/Yelp/dataset-examples/blob/master/json_to_csv_converter.py) 这段代码最初是与Python 2一起使用的,但是我正在使用Python 3。我进行了一些更改,因此它现在可以在Python 3中使用,除了我在字符串之前添加b'(这表明它是字节序列)之外。

我添加了encoding ='utf-8'将其转换为字符串,但是我的csv文件仍然显示b''

示例:business_id
b'7KPBkxAOEtb3QeIL9PEErg'

我需要更改什么以使其写字符串而不是字节?

谢谢

# -*- coding: utf-8 -*-
"""Convert the Yelp Dataset Challenge dataset from json format to csv.
For more information on the Yelp Dataset Challenge please visit http://yelp.com/dataset_challenge
"""
import argparse
import collections
import csv
import json


def read_and_write_file(json_file_path, csv_file_path, column_names):
    """Read in the json dataset file and write it out to a csv file, given the column names."""
    with open(csv_file_path, 'w', newline='', encoding='utf-8') as fout:
        csv_file = csv.writer(fout)
        csv_file.writerow(list(column_names))
        with open(json_file_path,encoding='utf-8') as fin:
            for line in fin:
                line_contents = json.loads(line)
                csv_file.writerow(get_row(line_contents, column_names))

def get_superset_of_column_names_from_file(json_file_path):
    """Read in the json dataset file and return the superset of column names."""
    column_names = set()
    with open(json_file_path, encoding='utf-8') as fin:
        for line in fin:
            line_contents = json.loads(line)
            column_names.update(
                    set(get_column_names(line_contents).keys())
                    )
    return column_names

def get_column_names(line_contents, parent_key=''):
    """Return a list of flattened key names given a dict.
    Example:
        line_contents = {
            'a': {
                'b': 2,
                'c': 3,
                },
        }
        will return: ['a.b', 'a.c']
    These will be the column names for the eventual csv file.
    """
    column_names = []
    for k, v in line_contents.items():
        column_name = "{0}.{1}".format(parent_key, k) if parent_key else k
        if isinstance(v, collections.MutableMapping):
            column_names.extend(
                    get_column_names(v, column_name).items()
                    )
        else:
            column_names.append((column_name, v))
    return dict(column_names)

def get_nested_value(d, key):
    """Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`.

    Example:
        d = {
            'a': {
                'b': 2,
                'c': 3,
                },
        }
        key = 'a.b'
        will return: 2

    """
    if '.' not in key:
        if key not in d:
            return None
        return d[key]
    base_key, sub_key = key.split('.', 1)
    if base_key not in d:
        return None
    sub_dict = d[base_key]
    return get_nested_value(sub_dict, sub_key)

def get_row(line_contents, column_names):
    """Return a csv compatible row given column names and a dict."""
    row = []
    for column_name in column_names:
        line_value = get_nested_value(
                        line_contents,
                        column_name,
                        )
        if isinstance(line_value, str):
            row.append('{0}'.format(line_value.encode('utf-8')))
        elif line_value is not None:
            row.append('{0}'.format(line_value))
        else:
            row.append('')
    return row

if __name__ == '__main__':
    """Convert a yelp dataset file from json to csv."""

    parser = argparse.ArgumentParser(
            description='Convert Yelp Dataset Challenge data from JSON format to CSV.',
            )

    parser.add_argument(
            'json_file',
            type=str,
            help='The json file to convert.',
            )

    args = parser.parse_args()

    json_file = args.json_file
    csv_file = '{0}.csv'.format(json_file.split('.json')[0])

    column_names = get_superset_of_column_names_from_file(json_file)
    read_and_write_file(json_file, csv_file, column_names)

1 个答案:

答案 0 :(得分:1)

一个猜测:

if isinstance(line_value, str):
    row.append('{0}'.format(line_value.encode('utf-8')))

如果值为str,则无需在Python 3中对其进行编码-Python 3中的所有字符串均为unicode。您可能应该检查该值是否是bytes的实例。

if isinstance(line_value, bytes):
    row.append('{0}'.format(line_value.decode('utf-8')))

[更新]

  

不,那条线正在检查它是否是字符串与数字的比较……所以str正确– Luluperam

确定吗?可以说line_value是字符串"foo"

line_value = 'foo'

现在尝试:

>>> row = []
>>> if isinstance(line_value, str):
...    row.append('{0}'.format(line_value.encode('utf-8')))
>>> print(row)
["b'foo'"]

这是CSV文件中字节文字的来源。现在,让我尝试一下我建议的版本,然后再将其关闭:

>>> line_value = b'foo'
>>> row = []
>>> if isinstance(line_value, bytes):
...    row.append('{0}'.format(line_value.decode('utf-8')))
>>> print(row)
['foo']