【问题标题】:Trying to find human names in a file using ntlk尝试使用 nltk 在文件中查找人名
【发布时间】:2023-02-26 03:06:04
【问题描述】:

我想从文本文件中提取人名。由于某种原因,我得到一个空行作为输出。这是我的代码:

import nltk
import re
nltk.download('names')
nltk.download('punkt')
from nltk.corpus import names

# Create a list of male and female names from the nltk names corpus
male_names = names.words('male.txt')
female_names = names.words('female.txt')
all_names = set(male_names + female_names)

def flag_people_names(text):
    possible_names = []
    words = nltk.word_tokenize(text)
    for word in words:
        # Split the word by ' ', '.' or '_' and check each part
        parts = re.split('[ _.]', word)
        for part in parts:
            if part.lower() in all_names:
                possible_names.append(word)
                break
    return possible_names

# Read text file
with open('sample.txt', 'r') as file:
    text = file.read()

# Call function to flag possible names
names = flag_people_names(text)
print(names)

这是名为 sample.txt 的输入文件

James is a really nice guy
Gina is a friend of james.
Gina and james like to play with Andy.

我得到这个作为输出:

[]

我想要 James、Gina 和 Andy。

我在使用 python3.8.5 的 MAC Catalina 上。 知道什么在这里不起作用吗?

【问题讨论】:

  • NLTK 名称列表是小写的吗?

标签: python nlp


【解决方案1】:

尝试删除“part.lower()”中的“.lower()”,因为 NLTK 名称列表并非全部都是小写字母,而是适当的大写字母。

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多