【发布时间】:2013-12-15 22:50:45
【问题描述】:
我正在尝试从文本中提取人名。
有没有人推荐的方法?
这是我尝试过的(代码如下):
我正在使用nltk 查找标记为人的所有内容,然后生成该人所有 NNP 部分的列表。我跳过只有一个 NNP 的人,以避免抓住一个单独的姓氏。
我得到了不错的结果,但想知道是否有更好的方法来解决这个问题。
代码:
import nltk
from nameparser.parser import HumanName
def get_human_names(text):
tokens = nltk.tokenize.word_tokenize(text)
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos, binary = False)
person_list = []
person = []
name = ""
for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
for leaf in subtree.leaves():
person.append(leaf[0])
if len(person) > 1: #avoid grabbing lone surnames
for part in person:
name += part + ' '
if name[:-1] not in person_list:
person_list.append(name[:-1])
name = ''
person = []
return (person_list)
text = """
Some economists have responded positively to Bitcoin, including
Francois R. Velde, senior economist of the Federal Reserve in Chicago
who described it as "an elegant solution to the problem of creating a
digital currency." In November 2013 Richard Branson announced that
Virgin Galactic would accept Bitcoin as payment, saying that he had invested
in Bitcoin and found it "fascinating how a whole new global currency
has been created", encouraging others to also invest in Bitcoin.
Other economists commenting on Bitcoin have been critical.
Economist Paul Krugman has suggested that the structure of the currency
incentivizes hoarding and that its value derives from the expectation that
others will accept it as payment. Economist Larry Summers has expressed
a "wait and see" attitude when it comes to Bitcoin. Nick Colas, a market
strategist for ConvergEx Group, has remarked on the effect of increasing
use of Bitcoin and its restricted supply, noting, "When incremental
adoption meets relatively fixed supply, it should be no surprise that
prices go up. And that’s exactly what is happening to BTC prices."
"""
names = get_human_names(text)
print "LAST, FIRST"
for name in names:
last_first = HumanName(name).last + ', ' + HumanName(name).first
print last_first
输出:
LAST, FIRST
Velde, Francois
Branson, Richard
Galactic, Virgin
Krugman, Paul
Summers, Larry
Colas, Nick
除了维珍银河,这都是有效的输出。当然,在本文的上下文中,知道维珍银河不是人名是困难的(也许是不可能的)部分。
【问题讨论】:
-
虽然很有趣,但不清楚这里的实际问题是什么。 “让我的代码更好”的建议不太适合这个网站。
-
谢谢,基本上我的问题是:我想从文本中提取名称。这是我尝试过的,它工作正常,但不是非常好。有没有人会推荐的解决这个问题的替代方法?我将编辑问题以改进它。
-
感谢分享。我能够使用您的代码,但我遇到了两个需要修复的错误。首先我得到了错误:
SyntaxError: Non-ASCII character.... no encoding declared,通过在第 1 行添加修复:# -- coding: UTF-8 --然后我得到错误:NotImplementedError("Use label() to access a node label.,通过从第 17 行删除“节点”修复如下:for subtree in sentt.subtrees(filter=lambda t: t.label() == 'PERSON'): -
如果您希望今天使用此代码。确保将这些放在 import 语句之后。 nltk.download('朋克'); nltk.download('averaged_perceptron_tagger'); nltk.download('maxent_ne_chunker'); nltk.download('单词');除此之外,请确保将 t.node 替换为 t.label()