简单问题的Python正则表达式

2024-10-01 00:29:18 发布

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

我想让用户问一个简单的问题,这样我就可以从输入的字符串中提取一些标准元素。你知道吗

要输入的字符串示例:

  • 谁是黑暗骑士的导演?你知道吗
  • 中国的首都是什么?你知道吗
  • 谁是美国总统?你知道吗

正如你所看到的,有时是“谁”,有时是“什么”。我很可能在找“|”操作符。我需要从这些字符串中提取两个东西。“The”之后和“of”之前的单词,以及“of”之后的单词。你知道吗

例如:

第一句话:我希望提取"director"并将其放入名为Relation的变量中,提取"The Dark Knight"并将其放入名为Concept的变量中。你知道吗

期望输出:

RelationVar = "director"
ConceptVar = "The Dark Knight"

第二句话:我想提取“capital”,将其分配给变量“Relation”……并提取“China”并将其放入变量“Concept”。你知道吗

RelationVar = "capital"
ConceptVar = "China"

关于如何使用re.match函数有什么想法吗?或者其他方法?你知道吗


Tags: ofthe字符串用户标准单词conceptdirector
2条回答

你想把|用于who/what是正确的。regex的其余部分非常简单,为了清晰起见,这里有组名,但是您可以使用r"(?:Who|What) is the (.+) of (.+)[?]"。你知道吗

>>> r = r"(?:Who|What) is the (?P<RelationVar>.+) of (?P<ConceptVar>.+)[?]"
>>> l = ['Who is the director of The Dark Knight?', 'What is the capital of China?', 'Who is the president of USA?']
>>> [re.match(r, i).groupdict() for i in l]
[{'RelationVar': 'director', 'ConceptVar': 'The Dark Knight'}, {'RelationVar': 'capital', 'ConceptVar': 'China'}, {'RelationVar': 'president', 'ConceptVar': 'USA'}]

如果您还想捕获问题使用的是谁或什么,请将(?:Who|What)更改为(Who|What)。你知道吗

实际上,提取数据并将其分配给变量非常简单:

>>> m = re.match(r, "What is the capital of China?")
>>> d = m.groupdict()
>>> relation_var = d["RelationVar"]
>>> concept_var = d["ConceptVar"]
>>> relation_var
'capital'
>>> concept_var
'China'

这是脚本,您可以简单地使用|在括号内选择匹配一个。你知道吗

这对我很管用

import re
list = ['Who is the director of The Dark Knight?','What is the capital of China?','Who is the president of USA?']
for string in list:
    a = re.compile(r'(What|Who) is the (.+) of (.+)')
    nodes = a.findall(string);
    Relation = nodes[0][0]
    Concept = nodes[0][1]
    print Relation
    print Concept
    print '  '

致以最诚挚的问候:)

相关问题 更多 >