python - 使用正则表达式从 JSON 中删除字符串中的 Unicode\uxxxx

标签 python json regex unicode

我有一个名为 stream_key.json 的存储文本数据的 JSON 文件:

{"text":"RT @WBali: Ideas for easter? Digging in with Seminyak\u2019s best beachfront view? \nRSVP: b&f.wbali@whotels.com https:\/\/t.co\/fRoAanOkyC"}

我们可以看到 json 文件中的文本包含 unicode \u2019,我想在 Python 2.7 中使用正则表达式删除此代码,这是我目前的代码 (eraseunicode.py):

import re
import json

def removeunicode(text):
    text = re.sub(r'\\[u]\S\S\S\S[s]', "", text)
    text = re.sub(r'\\[u]\S\S\S\S', "", text)
    return text

with open('stream_key.json', 'r') as f:
    for line in f:
        tweet = json.loads(line)
        text = tweet['text']
        text = removeunicode(text)
        print(text)

我得到的结果是:

Traceback (most recent call last):
  File "eraseunicode.py", line 17, in <module>
    print(text)
  File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2019' in position 53: character maps to <undefined>

因为我已经使用函数在打印前删除了\u2019,所以我不明白为什么它仍然是错误的。请帮忙。谢谢

最佳答案

当数据为文本文件时,\u2019为字符串。但是一旦加载到 json 中,它就变成了 unicode,替换就不再起作用了。

所以你必须在加载到 json 之前应用你的正则表达式 并且它可以工作

tweet = json.loads(removeunicode(line))

当然它会处理整个原始行。您还可以通过检查这样的字符代码(请注意,它并不严格等效)从解码的 text 中删除非 ascii 字符:

 text = "".join([x for x in tweet['text'] if ord(x)<128])

关于python - 使用正则表达式从 JSON 中删除字符串中的 Unicode\uxxxx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43340424/

相关文章:

python - 在 GeoPandas 中将 Legend 添加到 Choropleth map

python - 表格图像的格式问题

javascript - 如何获取 Backbone.Collection 的子集?

javascript 正则表达式——只生成 (.)+ 组中的最后一个字母?

python - 'function'对象在django中没有属性 'get'

javascript - 如何在 javascript 文件中输入 json 文件的正确路径

PHP 以 JSON 格式打印 SQL 查询

javascript - 如何将 '&amp;' 与 JS RegExp 匹配

java - (?i) 正则表达式结果 - "Nothing"被 Something 取代

python - 使用 Python 和 Tkinter 制作倒数计时器?