我有一个程序只从文件中提取那些pos标签存在pos-tags变量的单词。我的程序没有给出任何错误,但它也没有显示任何错误。它只执行。这是我的示例输入:
[['For,IN', ',,,', 'We,PRP', 'the,DT', 'divine,NN', 'caused,VBD', 'apostle,NN', 'We,PRP', 'vouchsafed,VBD', 'unto,JJ', 'Jesus,NNP', 'the,DT', 'son,NN', 'of,IN', 'Mary,NNP', 'all,DT', 'evidence,NN', 'of,IN', 'the,DT', 'truth,NN', ',,,', 'and,CC', 'strengthened,VBD', 'him,PRP', 'with,IN', 'holy,JJ'], [ 'be,VB', 'nor,CC', 'ransom,NN', 'taken,VBN', 'from,IN', 'them,PRP', 'and,CC', 'none,NN', '\n']]
这是我的代码:
import nltk
import os.path
import re
import os
sample_text4='E://QuranCopies45.txt'
file2 = open(sample_text4,'r',encoding='utf8')
arr=[]
for line in file2.readlines():
words=re.split(' ',line)
words=[line.replace('/',",")for line in words]
arr.append(words)
pos_tags = ('NN', 'NNP', 'NNS', 'NNPS')
nouns=[s.split(',')[0] for sub in arr for s in sub if s.endswith(pos_tags)]
print(nouns)
这是我的预期输出:
[ 'divine', 'apostle','Jesus', 'son','Mary', 'evidence', 'truth', 'ransom', 'none']
答案 0 :(得分:1)
您真的很接近,但您需要修复if
声明。目标是检查这些列表项中是否存在来自pos_tags
的任何元素...所以,使用any
!
>>> [j.split(',')[0] for i in arr for j in i if any(j.endswith(p) for p in pos_tags)]
['divine',
'apostle',
'Jesus',
'son',
'Mary',
'evidence',
'truth',
'ransom',
'none']
any
执行短路比较,检查pos_tags
中的任何元素是否出现在列表项的末尾。 any
在找到满足条件的标记时返回True
。否则,如果在迭代pos_tags
后,没有任何条件为True
,则any
会返回False
。
有关详细信息,请参阅How do Python's any and all functions work?。