python - 使用 python2.7 和 nltk 将代词替换为其先行词

标签 python python-2.7 nlp nltk

如标题所示,我正在尝试在字符串中查找代词并将其替换为它的先行词,例如:

[in]: "the princess looked from the palace, she was happy".
[out]: "the princess looked from the palace, the princess was happy". 

我使用 pos 标签返回代词和名词。我需要知道如何在不知道句子的情况下替换,意思是如何在句子中指定主语以用它替换代词。有什么建议吗?

最佳答案

我不知道 nltk 包(从未使用过),但它似乎可以立即给出您的答案。如果您查看 nltk.org 上的解析树示例,它表明主题已成功标记为“NP-SBJ”标签。这不是你要找的吗?

(早些时候,我忽略了标题中的 'nltk' 部分,我将这部分写在下面。我认为作为对如何解决此类问题的一般介绍可能会很有趣(尤其是如果您不有可用的包裹),所以我会把它留在这里:)

与 Python 问题相比,这更像是一个“自然语言”(即英语)问题。你能更具体地说明你期望什么样的句子吗?它应该适用于所有可能的英语句子吗?我认为这真的很难。

如果句子足够“简单”,假设第一个动词之前的所有内容都是主语就足够了。这适用于您的示例,但不适用于以下句子:

yesterday the princess looked from the palace, she was happy.
the princes who drank tea looked from the palace, she was happy.

(注意后一句的主语是“喝茶的公主”,“喝茶的”部分是“形容词短语”)。

此外,指定如果代词不指向主语(例如指向宾语)时应该发生什么:

the princess looked at the prince, he was happy.

为了在最一般的情况下解决你的问题,你应该找到(或制作)英语(或任何其他)语言的正式规范,它可以准确地告诉你句子的哪一部分是主语,动词, object etc. 例如:很多简单的英语句子都是这样的形式(括号[]之间的部分是可选的,括号()之间的部分是选择,即(the|a)表示你应该选择'the'或'a '):

sentence := subject verb [object]

规范右侧的每个部分都需要更详细地说明,例如:

subject, object := (noun_part_of_sentence|noun_part_of_sentence_plural)
noun_part_of_sentence := article [adjectivelist] [noun_modifier] noun # I guess there is a formal name for this...
noun_part_of_sentence_plural := [adjectivelist] [noun_modifier] noun_plural # note: no article
adjectivelist:= adjective [adjectivelist] # i.e., one or more adjectives

对于更复杂的句子,比如上面那个带有形容词短语的句子,上面的规范是不够的,应该是这样的:

noun_part_of_sentence := (the|a) [adjectivelist] [noun_modifier] [noun] [adjective_phrase]
adjective_phrase := relative_pronoun verb [object]
relative_pronoun := (who|which|that)

请注意,上面的规范已经非常强大:(如果你能够正确识别每个词的类型,例如动词、名词、冠词等)它可以成功检测以下句子:

The princess drank the tea.
The beautiful princess drank the tea.
The beautiful princess drank delicious the tea.
A beautiful princess drank delicious the lemon tea.
The beautiful princess who saw the handsome prince drank the refreshing tea.
The beautiful princess who saw the handsome prince who made the tea drank the refreshing tea.

但是,它不允许(尚未)出现诸如“公主看了宫殿”、“公主喝了茶”(注意:不是“茶”)和无数其他句子。诀窍是将您的形式规范扩展到足以满足您期望的句子类型的级别。

成功解析句子后,您(因此)知道主语是什么,任何代词,您可以进行替换。但是请注意,英语不是明确的,例如:

The princess looked at her mother, she was happy.

她指的是公主还是她的母亲?

祝你好运!

附言英语不是我的母语,所以我希望我对所有事情都使用了正确的术语!

关于python - 使用 python2.7 和 nltk 将代词替换为其先行词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15860695/

相关文章:

nlp - 带有子实体的 Luis 实体?

java - 使用 OpenNLP 从解析的内容中删除停用词

python - 如何从单个输入值获取分类报告

python - 模拟另一个函数内部的函数

python - 在 Python 3 中绘制罂粟花

Python3 在打印十六进制值时添加了额外的字节

python - if 语句未命中中的 continue 断点

python - 使用Python从docx解析表

python - 无法在 API 模式下使用 Xbee 发送/接收(python)

python - 按日期分组数据并在 python 中找到平均值