匹配单词变体的正则表达式

2024-05-11 19:41:37 发布

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

我有几个句子的格式:

Visa requirements for Qatari citizens are administrative entry restrictions by the authorities of other states placed on citizens of the Qatar.

Visa requirements for British citizens are administrative entry restrictions by the authorities of other states placed on citizens of the United Kingdom.

Visa requirements for Belarusian citizens are administrative entry restrictions imposed on citizens of Belarus by the authorities of other states.

我只想把上面句子中的“公民[国家名称]”匹配起来。正如你所看到的,有些国家以句号“中国公民”结尾,有些则延续,有些用“the”这样的词,有些国家有两个或两个以上的词,如“英国”。在

如何编写一个(pythonic)regex,它将匹配上述所有语句及其变体中的“citilities of COUNTRY_NAME”?在


Tags: oftheforbyonvisaarerequirements
1条回答
网友
1楼 · 发布于 2024-05-11 19:41:37

{{a1}我们可以使用^ a2}模块。在

我们假设国家名称是多个连续的单词,每个单词都以大写字母开头,并用一些空格隔开。如果你不能做出这样的假设,那就随意调整一下。如果您已经有一个国家列表,那么只要.{,40}匹配国家部分(或其他一些合理的限制)并检查某个国家是否是子字符串。在

import regex as re

text = '''Visa requirements...'''
country_pat = r'citizens of (?:the )?((?:\p{Lu}\p{L}+(?:\s*))+)'
print(country_pat.findall(text))

^{}表示我们不匹配该部分,p{Lu}和{}分别是Unicode大写字母和字母。在

相关问题 更多 >