匹配特定单词前的最后一个名词

2024-09-20 22:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python,希望匹配“needing”之前的最后一个名词。你知道吗

text = "Charles and Kim are needing a good hot dog"

我必须用关于芬德尔和nltk

我试过了,但显示了所有的信息之前,我只需要最后一个名词

post = re.findall(r'.*needing', text)[0]

我希望得到

Kim

Tags: andtextre信息postaregooddog
1条回答
网友
1楼 · 发布于 2024-09-20 22:21:22

只需使用nltk的词性标记。你知道吗

您需要下载一些nltk资源,然后标记并找到您想要的。此代码将执行以下操作:

import nltk

# You'll need to run these two resource downloads the first time you do this.
# So uncomment the following two lines

# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')


text = "Charles and Kim are needing a good hot dog"
tokens = nltk.word_tokenize(text)
tags = nltk.pos_tag(tokens)

# You are interested in splitting the sentence here
sentence_split = tokens.index("needing")

# Find the words where tag meets your criteria (must be a noun / proper noun)
nouns_before_split = [word for (word, tag) in tags[:sentence_split] if   tag.startswith('NN')]

# Show the result. The last such noun
print(nouns_before_split[-1])

相关问题 更多 >

    热门问题