Mon*_*y T 9 python nlp nltk python-2.7
正如标题所示我试图在一个字符串中寻找代词并用它的前身代替它:
[in]: "the princess looked from the palace, she was happy".
[out]: "the princess looked from the palace, the princess was happy".
Run Code Online (Sandbox Code Playgroud)
我使用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.
Run Code Online (Sandbox Code Playgroud)
(注意后一句的主语是“喝茶的公主”,“喝茶的”部分是“形容词短语”)。
此外,指定如果代词不指向主语(但例如指向宾语)会发生什么:
the princess looked at the prince, he was happy.
Run Code Online (Sandbox Code Playgroud)
为了在最一般的情况下解决您的问题,您应该找到(或制作)英语(或任何其他)语言的正式规范,它可以准确地告诉您句子的哪一部分是主语、动词、宾语等. 例子:很多简单的英语句子都是这样的形式(括号[]之间的部分是可选的,括号()之间的部分是选择,即,(the|a)表示你应该选择'the'或'a'):
sentence := subject verb [object]
Run Code Online (Sandbox Code Playgroud)
规范右侧的每个部分都需要更详细地指定,例如:
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
Run Code Online (Sandbox Code Playgroud)
对于更复杂的句子,例如上面带有形容词短语的句子,上面的说明是不够的,应该是这样的:
noun_part_of_sentence := (the|a) [adjectivelist] [noun_modifier] [noun] [adjective_phrase]
adjective_phrase := relative_pronoun verb [object]
relative_pronoun := (who|which|that)
Run Code Online (Sandbox Code Playgroud)
请注意,上面的规范已经非常强大了:(如果您能够正确识别每个单词的类型,例如动词、名词、冠词等)它可以成功检测以下句子:
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.
Run Code Online (Sandbox Code Playgroud)
但是,它不允许(还)诸如“公主看着宫殿”、“公主喝茶”(注意:不是“茶”)和无限其他的句子。诀窍是将您的正式规范扩展到足以满足您期望的句子类型的级别。
成功解析句子后,您(因此)知道主语,任何代词,并且可以进行替换。但是请注意,英语不是明确的,例如:
The princess looked at her mother, she was happy.
Run Code Online (Sandbox Code Playgroud)
她指的是公主还是她的母亲?
祝你好运!
PS 英语不是我的母语,所以我希望我对一切都使用了正确的术语!
| 归档时间: |
|
| 查看次数: |
2800 次 |
| 最近记录: |