首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索列表中的单词

搜索列表中的单词
EN

Stack Overflow用户
提问于 2018-04-06 00:02:56
回答 2查看 321关注 0票数 0

我有一个从utf-8文件生成的查找列表

代码语言:javascript
复制
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‘

代码语言:javascript
复制
word='الو'
for w in newStopWords1d:
    if word == w.encode("utf-8"):
        print 'found'

这个词找不到,我试过了

代码语言:javascript
复制
    if word in newStopWords1d:
        print 'found'

但这个词再一次看不见了。这似乎是编码的问题,但我无法解决。你能帮帮我吗。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-06 00:23:05

值得一提的是您使用了Python2.7。

代码语言:javascript
复制
word='الو'
for w in newStopWords1d:
    if word == w.decode("utf-8"):
        print 'found'

更好的解决方案是使用io中的开放函数

代码语言:javascript
复制
import io

with io.open('stop_word_Tiba.txt', encoding="utf-8") as f:
    ...

codecs模块

代码语言:javascript
复制
import codecs

with codecs.open('stop_word_Tiba.txt', encoding="utf-8") as f:
    ...

由于Python2.7中内置的开放函数不支持指定编码。

票数 0
EN

Stack Overflow用户

发布于 2018-04-06 01:35:38

通过将打开的文件语句编辑为

代码语言:javascript
复制
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'

谢谢你..。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49683312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档