如何只从文件中检索那些有名词标签的单词?

问题描述 投票:1回答:1

我有一个程序只从文件中提取那些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']
python arrays pos-tagger
1个回答
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?

© www.soinside.com 2019 - 2024. All rights reserved.