如何只从文件中检索那些有名词标签的词?
How to retrieve only those words from file which have noun tags?
我有一个程序只从文件中提取那些有 pos 标签的单词。我的程序没有给出任何错误,但也没有显示任何内容。它只执行。这是我的示例输入:
[['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
声明。目标是检查 any 来自 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
returns True
找到满足条件的标签的那一刻。否则,如果遍历pos_tags
后,none的条件为True
,则any
returns False
.
有关详细信息,请参阅 How do Python's any and all functions work?。
我有一个程序只从文件中提取那些有 pos 标签的单词。我的程序没有给出任何错误,但也没有显示任何内容。它只执行。这是我的示例输入:
[['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
声明。目标是检查 any 来自 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
returns True
找到满足条件的标签的那一刻。否则,如果遍历pos_tags
后,none的条件为True
,则any
returns False
.
有关详细信息,请参阅 How do Python's any and all functions work?。