Skip to main content
 首页 » 编程设计

python之遍历python列表

2024年11月01日7thcjp

我有如下 UTF-8 Unicode 文本文件(非英文)

所以我在 python 中将编码标记为 UTF-8,并将文件导入 python。

# -*- coding: utf-8 -*- 

我用“.”标记了句子。并得到句子的列表。

现在我需要与另一个 unicode 单词列表进行比较,并找出每个句子中是否有这些单词。

这是我的代码。但它仅显示识别出的第一个匹配项。

for sentence in sentences: 
    for word in sentence.split(" "): 
        if word in pronouns: 
            print sentence 

编辑:

最后我注意到源文本文件中存在无效的 unicode 字符。 这里描述了Tokenizing unicode using nltk

请您参考如下方法:

我试图模拟你的问题,但我得到了预期的结果,也许问题出在编码或你的代词列表中。

pronouns = ['aa','bb','cc'] 
 
sentences = ['aa dkdje asdf aesr','bb asersada','cc ase aser sa sa c ','aa saef sf se s', 'aa','bb'] 
 
for sentence in sentences: 
    for word in sentence.split(" "): 
        if word in pronouns: 
            print (sentence) 

代码的输出是:

aa dkdje asdf aesr 
bb asersada 
cc ase aser sa sa c  
aa saef sf se s 
aa 
bb 

希望对您有所帮助。