我有一个从utf-8文件生成的查找列表
with open('stop_word_Tiba.txt') as f:
newStopWords= list(itertools.chain( line.split() for line in f)) #save the file as list of lines
newStopWords1d=list(itertools.chain(*newStopWords)) # convert 2d list to 1d list当我打开文件时,我看到单词'الو‘在那里。现在的列表看起来是‘\xd9 8\xa3 7\xd9 9\xd9 9\x88’、‘\xd9 8\xa3 3\xd9 9\xd9 9\x88’、‘\xd9 8\xd9 7\xd9\xd9\x88\xd9\xd9\x8a’、‘\xd9 8\xa3 7\xd9 9\x84’、‘\xd9 8\xa3 7\xd9 9\x87’、‘\xd9 8\xd9 3\xd9 9\x87’、‘\xd9 9\xd9\x9\x88’、‘xd9 8\xd9 9\xd9\x87’、‘\xd9 8\xd9 9\xd8’、‘xd9 8\xd9 9\xd9\x87’、‘xd9\xd8\xd88’、‘xd9 8\xd9 9\xd8’、‘\xd9 8\xd9 9\xd9 87’、‘\xd9 8\xd9 9\xd8’、‘xd9\xd84\xd88’、‘xd9 8\xd9 9\xd8’、‘xd9 8\xd9 9\x87’、‘\xd9 8\xd9 9\x87’、‘\xd9 9\xd8\x88’、‘xd9 8\xd9 7\xd9 9\x87’、‘\x‘xd8 8\x8a 3\xd8 9\x88\xd8 9\xd83\xd8 9\x8a’,‘\xd8 9\x88’
然后,我想搜索一个特定的单词是否在newStopWords1d中,单词'الو‘是’\xd9 8\xa7 7\xd9 9\x88‘
word='الو'
for w in newStopWords1d:
if word == w.encode("utf-8"):
print 'found'这个词找不到,我试过了
if word in newStopWords1d:
print 'found'但这个词再一次看不见了。这似乎是编码的问题,但我无法解决。你能帮帮我吗。
发布于 2018-04-06 00:23:05
值得一提的是您使用了Python2.7。
word='الو'
for w in newStopWords1d:
if word == w.decode("utf-8"):
print 'found'更好的解决方案是使用io中的开放函数
import io
with io.open('stop_word_Tiba.txt', encoding="utf-8") as f:
...或codecs模块
import codecs
with codecs.open('stop_word_Tiba.txt', encoding="utf-8") as f:
...由于Python2.7中内置的开放函数不支持指定编码。
发布于 2018-04-06 01:35:38
通过将打开的文件语句编辑为
with codecs.open("stop_word_Tiba.txt", "r", "utf-8") as f:
newStopWords= list(itertools.chain( line.split() for line in f)) #save the file as list of lines
newStopWords1d=list(itertools.chain(*newStopWords))
for w in newStopWords1d:
if word.encode("utf-8") == w.encode("utf-8") :
return 'found'谢谢你..。
https://stackoverflow.com/questions/49683312
复制相似问题