Skip to main content
 首页 » 编程设计

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

2025年02月15日21powertoolsteam

我有一个名为 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])