python - 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 新手。提前致谢。
解决方案
在我个人看来,最好使用 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.
推荐阅读
- python - 分组数据并求和
- android - Flutter setState()函数不起作用:W / IInputConnectionWrapper(4965):getTextBeforeCursor on inactive InputConnection错误
- javascript - 为什么 chrome 任务管理器内存占用显着增加(170mb)仅在一个 div 的 innerHTML 中呈现 10mb 字符串?
- arrays - 比较两个数组,记住 Ruby 中一个数组的顺序
- c++ - gmock:使用 unique_ptr 时 EXPECT_CALL 崩溃
- protocol-buffers - Protobuf 3 java:如何仅区分和更新输入对象中的那些字段?场景:例如持久化到数据库
- salt-stack - 盐状态不能与支柱数据结合使用
- reporting-services - SSRS Visual Studio 2017 (SSDT) - 日期参数格式
- javascript - 我想在 Click 事件上从 html 按钮调用 javascript 类,该怎么做?
- scala.js - 未在 scalajs 中导出本机 javascript 类