gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:29:58 24 4
gpt4 key购买 nike

我正在尝试从包含推文的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com