Skip to main content
 首页 » 编程设计

python之正则表达式之在文本中搜索相似的国家名称

2024年12月31日27mayingbao

我想从预定义国家/地区列表中识别出现在文本中的国家/地区。 问题是,有些名字非常相似,所以如果文本中有一个国家,它也会识别出另一个国家。 例如:

text1 = "The disease has spread to three countries: Guinea, Guinea-Bassau and Equatorial Guinea." 
 
text2 = "Only Guinea-Bassau and Equatorial Guinea contained strains of the virus." 
 
list_of_countries = ['Guinea', 'Guinea-Bassau', 'Equatorial Guinea'] 

我还没有想出一个代码来返回 text1 的所有三个列表项,但只为 text2 返回“Guinea-Bassau”和“Equatorial Guinea”。

这只是一个具体的例子。我当然可以为非洲的 3 个几内亚国家的具体问题创建一个临时解决方案,但问题将返回到“刚果共和国”和“刚果民主共和国”等。

编辑:我想到解决这个问题的一种方法是删除/丢弃文本中的任何实例,一旦它匹配可能的最长命名国家/地区。

请您参考如下方法:

你可以使用

import re 
 
text1 = "The disease has spread to three countries: Guinea, Guinea-Bassau and Equatorial Guinea." 
text2 = "Only Guinea-Bassau and Equatorial Guinea contained strains of the virus." 
list_of_countries = ['Guinea', 'Guinea-Bassau', 'Equatorial Guinea'] 
 
# Sort the list by length in descending order 
list_of_countries=sorted(list_of_countries,key=len,reverse=True) 
# Build the alternation based regex with \b to match each item as a whole word  
rx=r'\b(?:{})\b'.format("|".join(list_of_countries)) 
print(re.findall(rx, text1)) 
# => ['Guinea', 'Guinea-Bassau', 'Equatorial Guinea'] 
print(re.findall(rx, text2)) 
# => ['Guinea-Bassau', 'Equatorial Guinea'] 

参见 Python demo

请注意,按长度降序对 list_of_countries 列表进行排序很重要,因为列表中的项目可能有空格并且可能从字符串中的相同位置开始。

形成的正则表达式是

\b(?:Equatorial Guinea|Guinea-Bassau|Guinea)\b 

参见 regex demo

详情

  • \b - 单词边界
  • (?: - 非捕获组的开始,以便可以将单词边界应用于每个备选方案
    • 赤道几内亚
    • | - 或者
    • 几内亚巴绍
    • | - 或
    • 几内亚
  • ) - 组结束
  • \b - 单词边界。