Jos*_* K. 4 python bash json utf-8
我想分析 .jsonl 文档中的文本(使用 Python 3)。只要文本是英文,我运行的代码就可以正常工作,但对于阿拉伯文本文件,我收到错误消息:json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 列 1(字符 0)
我通读了一些线程并认为我可能需要解码它,我确实将 .decode(utf-8-sig) 添加到 json.loads (见代码)。这样做会导致以下错误消息:AttributeError: 'str' object has no attribute '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))
Run Code Online (Sandbox Code Playgroud)
您可以使用io.openwhich 支持动态解码(通过encoding参数),在 Python 2 和 Python 3 中(实际上,在 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)
# ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6546 次 |
| 最近记录: |