python 错误;统一码编码错误 : 'ascii' codec can't encode character u'\u2026'

标签 python csv encoding utf-8

我正在尝试从包含推文的 JSON 文件中提取一些数据并将其写入 csv。该文件包含各种字符,我猜这就是我收到此错误消息的原因:

UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'\u2026'

我想我必须在写入 csv 文件之前将输出转换为 utf-8,但我无法做到这一点。我在 stackoverflow 上发现了类似的问题,但不是我无法针对我的问题调整解决方案(我应该补充一点,我对 python 并不熟悉。我是一名社会科学家,而不是程序员)

import csv
import json

fieldnames = ['id', 'text']

with open('MY_SOURCE_FILE', 'r') as f, open('MY_OUTPUT', 'a') as out:

    writer = csv.DictWriter(
                    out, fieldnames=fieldnames, delimiter=',', quoting=csv.QUOTE_ALL)

    for line in f:
        tweet = json.loads(line)
        user = tweet['user']
        output = {
            'text': tweet['text'],
            'id': tweet['id'],
        }
        writer.writerow(output)

最佳答案

您只需要将文本编码为 utf-8:

for line in f:
    tweet = json.loads(line)
    user = tweet['user']
    output = {
        'text': tweet['text'].encode("utf-8"),
        'id': tweet['id'],
    }
    writer.writerow(output)

csv模块不支持在python2中写unicode:

Note This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

关于 python 错误;统一码编码错误 : 'ascii' codec can't encode character u'\u2026',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876278/

相关文章:

python - 在Tensorflow中,如何解开tf.nn.max_pool_with_argmax得到的扁平化指标?

python - 如何使用正则表达式在python中搜索两位数?

python - 在Python中上传和读取csv文件

javascript - 如何在 Javascript 中将 CSV 文件解析为数组

c# - WebClient.DownloadString 结果与浏览器结果 2 不匹配

c# - Base64 编码对编码有字符串长度限制吗?

xml - 提取响应的编码转换

python - 将 python 可视化面板保存为 html

python - 使用 python SMTP 发送电子邮件时遇到问题

sql-server - SQL - 将字符串分隔成列