我在一个列表中有几个属于 '\uword' 类型的单词。我想用空字符串替换 '\u'。我环顾四周,但到目前为止对我没有任何帮助。我尝试使用 "%r"%word 转换为原始字符串,但这没有用。我也尝试使用 word.encode('unicode-escape') 但没有得到任何结果。有什么想法吗?
编辑
添加代码
word = '\u2019'
word.encode('unicode-escape')
print(word) # error
word = '\u2019'
word = "%r"%word
print(word) # error
请您参考如下方法:
我在假设字符串的 .encode 方法修改字符串时犯了一个错误,类似于列表的 .sort() 方法。但是根据文档
The opposite method of bytes.decode() is str.encode(), which returns a bytes representation of the Unicode string, encoded in the requested encoding.
def remove_u(word):
word_u = (word.encode('unicode-escape')).decode("utf-8", "strict")
if r'\u' in word_u:
# print(True)
return word_u.split('\\u')[1]
return word
vocabulary_ = [remove_u(each_word) for each_word in vocabulary_]
