【问题标题】:Extracting human names from text data using python stanza使用 python 节从文本数据中提取人名
【发布时间】:2021-06-30 13:13:59
【问题描述】:

我有一个包含书名页字符串值的数据集(例如,书名页上的所有单词,我的 txt 文件的每一行都是不同的书)。从这里我试图检索作者的姓名作为出现在标题页上的人名,并将每个姓名存储在 csv 文件中的单独行上。当我键入以下代码时,我会为每个条目获得一个“无作者”值,这根据输入数据是不合理的。有人可以帮我弄清楚出了什么问题吗?谢谢,过去几天我一直在为此绞尽脑汁,但没有任何结果。

import stanza 
import csv
stanza.download('en') 

nlp = stanza.Pipeline('en')

def get_human_names(text,output):
    with open(text, 'r', encoding = "ISO-8859-1") as txt_file:
        Lines=txt_file.readlines()
        person_list=[]
        for line in Lines:
            doc=nlp(str(line))
            for sent in doc.sentences:
                for token in sent.tokens:
                    if {token.ner}=='B-PERSON' or {token.ner}=='E-PERSON':
                        person_list.append({token.text})
                if(len(person_list)==0): ## avoid skipping entries in the output file
                    person_list=["no author"]
            with open(output, 'a') as csv_output:
                writer=csv.writer(csv_output)
                writer.writerow(person_list)

get_human_names('/Users/tancredirapone/Desktop/LoC_Project/titles.txt','/Users/tancredirapone/Desktop/LoC_Project/titles_author_stanza.csv')

【问题讨论】:

    标签: python stanford-nlp


    【解决方案1】:

    万一有人遇到类似问题...这似乎可行,但结果并不完全令人满意(即遗漏了几个名字)。我不知道这是因为我写的代码还是只是偶尔缺少名称,但我怀疑是后者。

    import csv
    import stanza
    stanza.download('en')
    nlp=stanza.Pipeline('en')
    
    
    with open('/Users/tancredirapone/Desktop/LoC_Project/titles.csv', 'r', encoding = "ISO-8859-1") as txt_file:
            reader=csv.reader(txt_file)
            for row in reader:
                person_list=[]
                doc=nlp(str(row))
                for i, sentence in enumerate(doc.sentences):
                    for token in sentence.tokens:
                        if "PERSON" in str({token.ner}):
                            person_list.append({token.text})
                if len(person_list)==0:
                    person_list=["no author"]
                with open('/Users/tancredirapone/Desktop/LoC_Project/author_names.csv', 'a') as csv_output:
                    writer=csv.writer(csv_output)
                    writer.writerow(person_list)
                person_list=[]   
    
    

    一种可能性是,节可能缺少外国名称,但据我所知,不可能创建具有多种语言的管道(nlp=stanza.Pipeline('en', 'de', 'fr' ... )。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多