gpt4 book ai didi

python - JSON解码错误 : Unexpected UTF-8 BOM: Display problems in bash?

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:30 30 4
gpt4 key购买 nike

我想分析 .jsonl 文档中的文本(使用 Python 3)。只要文本是英文,我运行的代码就可以正常工作,但对于阿拉伯文文本文件,我会收到错误消息:json.decoder.JSONDecodeError:意外的 UTF-8 BOM(使用 utf-8-sig 解码):第 1 行第 1 列(字符 0)

我通读了一些线程并认为我可能需要解码它,我确实将 .decode(utf-8-sig) 添加到 json.loads(参见代码)。这样做会导致以下错误消息:AttributeError: 'str' 对象没有属性 'decode'

我还在 ~/.bashrc 中将 LANG 设置更改为 utf8,以防它与 bash 终端无法正确显示字符但出现相同错误有关。

在此提前感谢代码!

import sys 
from collections import Counter
import json

def get_hashtags(tweet):
entities = tweet.get('entities', {})
hashtags = entities.get('hashtags', [])
return [tag['text'].lower() for tag in hashtags]


if __name__ == '__main__':
fname = sys.argv[1]
with open(fname, 'r') as f:
hashtags = Counter()
for line in f:
tweet = json.loads(line.decode('utf-8-sig'))
hashtags_in_tweet = get_hashtags(tweet)
hashtags.update(hashtags_in_tweet)
for tag, count in hashtags.most_common(20):
print("{}: {}".format(tag, count))

最佳答案

您可以使用 io.open它支持在 Python 2 和 Python 3 中即时解码(通过 encoding 参数)(实际上,在 Python 3 中,io.open 是默认的 open):

import io

with io.open(fname, 'r', encoding='utf-8-sig') as f:
# ...
for line in f:
tweet = json.loads(line)
# ...

关于python - JSON解码错误 : Unexpected UTF-8 BOM: Display problems in bash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46934135/

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