使用python和n从文本文件中提取候选对象的名称

2024-03-29 10:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

import re
import spacy
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk.corpus import wordnet

inputfile = open('inputfile.txt', 'r')
String= inputfile.read()
nlp = spacy.load('en_core_web_sm')

def candidate_name_extractor(input_string, nlp):
    input_string = str(input_string)

    doc = nlp(input_string)

    # Extract entities
    doc_entities = doc.ents

    # Subset to person type entities
    doc_persons = filter(lambda x: x.label_ == 'PERSON', doc_entities)
    doc_persons = filter(lambda x: len(x.text.strip().split()) >= 2, doc_persons)
    doc_persons = list(map(lambda x: x.text.strip(), doc_persons))
    print(doc_persons)
    # Assuming that the first Person entity with more than two tokens is the candidate's name
    candidate_name = doc_persons[0]
    return candidate_name

if __name__ == '__main__':
    names = candidate_name_extractor(String, nlp)

print(names)

我想从文本文件中提取候选者的名字,但是它返回了错误的值。当我用map删除list时,map也不工作并给出错误


Tags: lambdanamefromimportmapinputstringdoc
2条回答

从词性标注后获得的词表中,使用正则表达式提取所有带有名词性标记的单词:

Nouns_List = []

for Word in nltk.pos_tag(Words_List):
    if re.match('[NN.*]', Word[1]):
         Nouns_List.append(Word[0])

对于Nouns_List中的每个单词,检查它是否是英语单词。这可以通过检查synsets是否可用于wordnet中的该单词来完成:

^{pr2}$

由于印度名字不能作为英语词典中的词条,这可能是从文本中提取它们的一种可能的方法。在

import re
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk.corpus import wordnet

String = 'Ravana was killed in a war'

Sentences = nltk.sent_tokenize(String)
Tokens = []
for Sent in Sentences:
    Tokens.append(nltk.word_tokenize(Sent)) 
Words_List = [nltk.pos_tag(Token) for Token in Tokens]

Nouns_List = []

for List in Words_List:
    for Word in List:
        if re.match('[NN.*]', Word[1]):
             Nouns_List.append(Word[0])

Names = []
for Nouns in Nouns_List:
    if not wordnet.synsets(Nouns):
        Names.append(Nouns)

print (Names)

检查此代码。我得到Ravana作为输出。在

编辑:

我用简历中的几句话创建了一个文本文件,并将其作为输入输入输入到我的程序中。以下仅显示代码的更改部分:

^{pr2}$

它返回所有不在wordnet语料库中的名字,比如我的名字,我的房子的名字,地方,大学的名字和地点。在

相关问题 更多 >