gpt4 book ai didi

python - 使用 nltk 从文本文件中提取所有名词

转载 作者:太空狗 更新时间:2023-10-29 17:21:24 25 4
gpt4 key购买 nike

有没有更有效的方法?我的代码读取一个文本文件并提取所有名词。

import nltk

File = open(fileName) #open file
lines = File.read() #read all lines
sentences = nltk.sent_tokenize(lines) #tokenize sentences
nouns = [] #empty to array to hold all nouns

for sentence in sentences:
for word,pos in nltk.pos_tag(nltk.word_tokenize(str(sentence))):
if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS'):
nouns.append(word)

如何降低这段代码的时间复杂度?有没有办法避免使用嵌套的 for 循环?

提前致谢!

最佳答案

如果您对 NLTK 以外的选项持开放态度,请查看 TextBlob .它可以轻松提取所有名词和名词短语:

>>> from textblob import TextBlob
>>> txt = """Natural language processing (NLP) is a field of computer science, artificial intelligence, and computational linguistics concerned with the inter
actions between computers and human (natural) languages."""
>>> blob = TextBlob(txt)
>>> print(blob.noun_phrases)
[u'natural language processing', 'nlp', u'computer science', u'artificial intelligence', u'computational linguistics']

关于python - 使用 nltk 从文本文件中提取所有名词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com