我有一个程序只从文件中提取那些具有 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']
最佳答案
你已经很接近了,但你需要修复你的 if
陈述。目标是检查 pos_tags
中是否有任何元素存在于这些列表项中...所以,使用 any
!
>>> [j.split(',')[0] for i in arr for j in i if <b>any(j.endswith(p) for p in pos_tags)</b>]
['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? .
关于python - 如何从文件中仅检索那些带有名词标签的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47905790/