我知道可以使用名词提取从句子中获取名词,但如何使用句子覆盖/映射来提取短语呢?
例如:
句子覆盖:
"First, @action; Second, Foobar"
输入:
"First, Dance and Code; Second, Foobar"
我想返回:
action = "Dance and Code"
- 普通的名词提取方法不适用,因为提取的内容不总是名词
- 句子的表达方式不同,所以不能简单地使用 words[x] … 因为单词的位置会变化
回答:
你可以稍微改写你的字符串模板,将它们变成正则表达式,然后查看哪个(或哪些)匹配。
>>> 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
你甚至可以将现有的字符串转换成这种正则表达式(在转义正则表达式元字符如 .?*()
之后)。
>>> 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\.\.\.\)