我在这样的数据帧中有一列.

Text
"Lorum Ipsum Rotterdam dolor sit." 
"ed ut perspiciatis Boekarest, New York, consectetur adipiscing elit, sed " 
"Excepteur sint occaecat Glasgow cupidatat non proident, sunt in culpa"

我希望每个地理位置都被"GPE"所取代.

我正在使用spacy检测实体.这很好,如下所示.

nlp = spacy.load('en_core_web_lg')

for value in df['text']:
    doc = nlp(value)
    for ent in doc.ents:
        print(ent.text, ent.label_)
Output: 
Rotterdam GPE
Boekarest GPE
New York GPE
Glasgow GPE 

为了替换列中的城市名称,我try 了下面的代码,但它不起作用.

for value in df['text']:
    doc = nlp(value)
    for ent in doc.ents:
        for word in value.split():
            if ent.label_ == "GPE":
                word.replace(ent.label, "_GPE_")

有人知道我做错了什么吗?

推荐答案

您可以使用

import spacy, warnings
import pandas as pd
warnings.filterwarnings("ignore", 'User provided device_type of \'cuda\', but CUDA is not available. Disabling')

df = pd.DataFrame({'Text':["Lorum Ipsum Rotterdam dolor sit.", "ed ut perspiciatis Boekarest, New York, consectetur adipiscing elit, sed ", "Excepteur sint occaecat Glasgow cupidatat non proident, sunt in culpa"]})
nlp = spacy.load('en_core_web_lg')

def redact_gpe(text):
    doc = nlp(text)
    newString = text
    for e in reversed(doc.ents):
        if e.label_ == "GPE":
            start = e.start_char
            end = start + len(e.text)
            newString = f'{newString[:start]}GPE{newString[end:]}'
    return newString

df['Text'] = df['Text'].apply(redact_gpe)

输出:

                                                                   Text
0                                      Lorum Ipsum GPE dolor sit.
1  ed ut perspiciatis GPE, GPE, consectetur adipiscing elit, sed
2     Excepteur sint occaecat GPE cupidatat non proident, sunt in culpa

Python相关问答推荐

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

如何强制向量中的特定元素在Gekko中处于优化解决方案中

在极点中读取、扫描和接收有什么不同?

如果不使用. to_list()[0],我如何从一个pandas DataFrame中获取一个值?

Pandas:计数器的滚动和,复位

如何在Polars中创建条件增量列?

解析CSV文件以将详细信息添加到XML文件

ValueError:必须在Pandas 中生成聚合值

为什么fizzbuzz在两个数字的条件出现在一个数字的条件之后时不起作用?

大Pandas 每月重新抽样200万只和300万只

如何在开始迭代自定义迭代器类时重置索引属性?

突出显示两幅图像之间的变化或差异区域

在Matplotlib中通过特定的Y值而不是 colored颜色 来改变alpha/opacity

PYTORCH-张量问题-Mat1和Mat2形状不能相乘(8x10和8x8)

我怎样才能用python打印一个 map 对象?

在给定一组约束的情况下使用所有唯一组合创建数据帧

巨 Python 品脱摄氏度单位

基于直方图箱的样本数据

我正在试着做一个简单的程序来判断学校的一个项目的调查数据,但它不起作用,有人能帮我吗?

将GroupShuffleSplit与GridSearchCV和CROSS_VAL_SCORE一起使用以进行嵌套交叉验证