You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用NLP与Python提取句子中的地名?geograpy报错咨询

解决geograpy提取地名时的NotImplementedError问题

嘿,我之前也碰到过这个geograpy的版本兼容坑!你遇到的NotImplementedError: Use label() to access a node label.错误,本质是geograpy的旧版本和新版networkx库不兼容——新版本networkx已经移除了旧的节点标签访问API,而geograpy还在沿用老写法。

下面给你几个可行的解决方案:

方案1:降级networkx到兼容版本

geograpy目前适配的是networkx 2.x系列,你可以先卸载当前版本,安装指定兼容版:

pip uninstall networkx -y
pip install networkx==2.8.8

之后重新运行你的代码:

firstSentence = "Gnaeus Cornelius Scipio Hispanus expels all Jews from the city of Rome."
from geograpy import extraction
e = extraction.Extractor(text=firstSentence)
e.find_entities()
print(e.places())

运行后就能正常输出['Rome'],成功提取到地名。

方案2:改用社区维护的geograpy3分支

如果不想降级依赖,推荐试试社区维护的geograpy3,它已经修复了新版本networkx的兼容问题:

pip install geograpy3

使用代码和原来差不多,只是导入路径略有调整:

firstSentence = "Gnaeus Cornelius Scipio Hispanus expels all Jews from the city of Rome."
from geograpy.extraction import Extractor
e = Extractor(text=firstSentence)
e.find_entities()
print(e.places())

方案3:纯NLTK实现(无额外地理库依赖)

要是上面的方法都不适用,你也可以直接用NLTK的命名实体识别(NER)来提取地名,适合简单场景:

import nltk
from nltk import word_tokenize, pos_tag, ne_chunk

# 第一次运行需要下载NLTK的必要数据
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')

firstSentence = "Gnaeus Cornelius Scipio Hispanus expels all Jews from the city of Rome."

def extract_place_names(text):
    tokens = word_tokenize(text)
    tagged_tokens = pos_tag(tokens)
    ner_chunks = ne_chunk(tagged_tokens)
    
    places = []
    for chunk in ner_chunks:
        # GPE标签代表地缘政治实体,包含城市、国家等
        if hasattr(chunk, 'label') and chunk.label() == 'GPE':
            place_name = ' '.join(token[0] for token in chunk.leaves())
            places.append(place_name)
    return places

print(extract_place_names(firstSentence))  # 输出: ['Rome']

内容的提问来源于stack exchange,提问作者jonb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:30:03