如何从python中的字符串中提取国家/地区

Tal*_*abi 5 python

我有一些文本,其中可能包含也可能不包含国家/地区名称。例如:

' 尼日利亚:Hotspot Network LTD 农村电话可行性研究'

这就是我从中提取国名的方式。在我的第一次尝试中:

findcountry("Nigeria: Hotspot Network LTD Rural Telephony Feasibility Study")

def findCountry(stringText):
    for country in pycountry.countries:
        if country.name.lower() in stringText.lower():
            return country.name
    return None
Run Code Online (Sandbox Code Playgroud)

不幸的是,它给了我错误的输出,[Niger]而正确的输出是尼日利亚。注意尼日尔和尼日利亚是世界上两个不同的现有国家。

在第二次尝试中:

def findCountry(stringText):
    full_list =[]
    for country in pycountry.countries:
        if country.name.lower() in stringText.lower():
            full_list.append(country)

    if len(full_list) > 0:
        return full_list

    return None
Run Code Online (Sandbox Code Playgroud)

我得到['Niger', 'Nigeria']作为输出。但我找不到让尼日利亚作为我最终输出的方法。如何实现这一目标。

注意:这里我知道尼日利亚是正确的答案,但稍后我会将其放入代码中以选择文本中存在的最终国家名称,并且它应该具有非常高的检测准确度。

Ama*_*dan 6

总是先搜索最长的字符串;这将防止您遇到的那种错误。

countries = sorted(pycountry.countries, key=lambda x: -len(x))
Run Code Online (Sandbox Code Playgroud)