我想让用户问一个简单的问题,这样我就可以从输入的字符串中提取一些标准元素。你知道吗
要输入的字符串示例:
正如你所看到的,有时是“谁”,有时是“什么”。我很可能在找“|”操作符。我需要从这些字符串中提取两个东西。“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
函数有什么想法吗?或者其他方法?你知道吗
你想把
|
用于who/what是正确的。regex的其余部分非常简单,为了清晰起见,这里有组名,但是您可以使用r"(?:Who|What) is the (.+) of (.+)[?]"
。你知道吗如果您还想捕获问题使用的是谁或什么,请将
(?:Who|What)
更改为(Who|What)
。你知道吗实际上,提取数据并将其分配给变量非常简单:
这是脚本,您可以简单地使用|在括号内选择匹配一个。你知道吗
这对我很管用
致以最诚挚的问候:)
相关问题 更多 >
编程相关推荐