NLTK:如何根据句子地图提取信息?

时间:2016-07-10 11:39:18

标签: python nlp artificial-intelligence nltk

我知道你可以使用名词提取来从句子中取出名词,但是如何使用句子叠加/地图来取出短语呢?

例如:

  

句子叠加:

"First, @action; Second, Foobar"
     

输入:

"First, Dance and Code; Second, Foobar"
     

我想回复:

action = "Dance and Code"
  • 正常名词提取不会起作用,因为它不会永远是名词
  • 句子的措辞方式不同,所以它不能是单词[x] ......因为单词的位置发生了变化

1 个答案:

答案 0 :(得分:2)

您可以稍微重写字符串模板以将其转换为正则表达式,并查看哪一个(或哪些)匹配。

>>> template = "First, (?P<action>.*); Second, Foobar"
>>> mo = re.search(template, "First, Dance and Code; Second, Foobar")
>>> if mo:
        print(mo.group("action"))
Dance and Code

您甚至可以将现有字符串转换为此类正则表达式(在转义regexp元字符后再转换为.?*())。

>>> template = "First, @action; (Second, Foobar...)"
>>> re_template = re.sub(r"\\@(\w+)", r"(?P<\g<1>>.*)", re.escape(template))
>>> print(re_template)
First\,\ (?P<action>.*)\;\ \(Second\,\ Foobar\.\.\.\)
相关问题