首页 > 解决方案 > nltk : 根据 POS 用其他词替换标记

问题描述

我正在研究自然语言处理,需要预处理一些数据。我的数据在文本文件中,我必须读取数据并将所有名称更改为男性或女性。

读取数据并对其进行标记后,我应用 pos 标记并检查具有名称列表的文件并将名称更改为“男性”或“女性”

例如 :

['Jack', 'and', 'Jill', 'Went', 'up', 'the', 'hill']

应该改为

['Male', 'and', 'Female', 'Went', 'up', 'the', 'hill']

基于以下POS

[('Jack', 'NNP'), ('and', 'CC'), ('Jill', 'NNP'), ('Went', 'NNP'), ('up', 'IN') , ('the', 'DT'), ('hill', 'NN')]

我的代码如下:

import nltk

text = open('collegegirl.txt').read()

with open('male_names.txt') as f1:
    male = nltk.word_tokenize(f1.read())

with open('female_names.txt') as f2:
    female = nltk.word_tokenize(f2.read())  

data = nltk.pos_tag(nltk.word_tokenize(text))
for word, pos in data:
    if(pos == 'NNP'):
        if word in male:
            word = 'Male'
        if word in female:
            word = 'Female'

上面的代码只是检查单词而不是写任何东西。如何编辑数据中的名称。我是 python 新手。提前致谢。

标签: pythonnltk

解决方案


在我个人看来,最好使用 Spacy 进行 POS 标记,它更快更准确。此外,您可以使用其命名实体识别来检查单词是否为 PERSON。安装 spacy 并en_core_web_lg从这里下载模型https://spacy.io/usage/

您的问题可以通过以下方式解决:

import spacy
from functools import reduce

nlp_spacy = spacy.load('en_core_web_lg')

NAMELIST = {'Christiano Ronaldo':'Male', 'Neymar':'Male', 'Messi':'Male', "Sandra":'Female'}

with open("input.txt") as f:
    text = f.read()

doc = nlp_spacy(text)

names_in_text = [(entity.text, NAMELIST[entity.text])  for entity in doc.ents if entity.label_ in ['PERSON'] and entity.text in NAMELIST]
print(names_in_text)       #------- prints [('Christiano Ronaldo', 'Male'), ('Messi', 'Male')]

replaced_text = reduce(lambda x, kv: x.replace(*kv), names_in_text, text)
print(replaced_text)       #------- prints Male scored three. Male scored one. Female is an athlete. I am from US.

推荐阅读