如何用python提取文字中的动词及名词
Jump to turn (7)
- User
如何用python提取文字中的动词及名词
- Assistant
要提取文本中的动词和名词,可以使用Python中的自然语言处理库NLTK(Natural Language Toolkit)。
首先,你需要使用NLTK库进行安装,然后,使用以下代码:
pythonimport nltk from nltk.tag import pos_tag from nltk.tokenize import word_tokenize # 下载词性标注器 nltk.download('averaged_perceptron_tagger') def extract_verbs_and_nouns(text): # 分词 tokens = word_tokenize(text) # 词性标注 tagged_words = pos_tag(tokens) verbs = [] nouns = [] for word, tag in tagged_words: # 判断词性标签 if tag.startswith('V'): # 动词标签 verbs.append(word) elif tag.startswith('N'): # 名词标签 nouns.append(word) return verbs, nouns # 示例文本 text = "I am learning Python programming. Programming is fun." # 提取动词和名词 verbs, nouns = extract_verbs_and_nouns(text) print("动词:", verbs) print("名词:", nouns)