python - 如何从文件中仅检索那些带有名词标签的单词?

标签 python arrays pos-tagger

我有一个程序只从文件中提取那些具有 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/

相关文章:

python - 当 dtype=object 时,如何通过 numpy 数组广播函数?

python - 查找元组中第二个元素的最大值 - Python

python - plotly 图: Add grid

javascript - 如何循环遍历 2 个数组来创建新的键/值对象

javascript - 需要如何从 Viewdata 列表填充 javascript 数组的简单示例

nlp - 词性标记 : tagging unknown words

python - Asyncio协程从未等待错误

c - 使用指针访问数组中的数据

python - 从列表 pos_tag 序列列表中仅提取名词?

python - 为什么NLTK中的pos_tag将 "please"标记为NN?