【问题标题】:a python library that accepts some text, and replaces phone numbers, names, and so on with tokens一个 python 库,它接受一些文本,并用标记替换电话号码、姓名等
【发布时间】:2016-08-23 00:15:19
【问题描述】:

我需要一个 python 库来接受一些文本,并用标记替换电话号码、姓名等。示例:

输入:请拨打 0430013454 与罗伯特联系以进一步讨论此问题。

输出:请在 PHONE 上致电 NAME 以进一步讨论此问题。

换句话说,我需要一个句子,任何句子,然后程序将在该句子上运行并删除任何看起来像名字、电话号码或任何其他标识符的东西,并将其替换为令牌 I.E NAME电话号码所以该标记将只是替换信息的文本,因此不再显示。

必须与 python 2.7 兼容。有人知道这将如何完成吗?

干杯!

【问题讨论】:

  • 你能再具体一点吗?我真的不明白。你只是想用' '替换名字和号码吗? “代币”是什么意思?
  • 谁会赞成这样一个明显跑题的问题?
  • 提问前请阅读stackoverflow.com/help/how-to-ask
  • "等等..." 那么,你想要一个能猜出你想要什么的库吗?
  • 对不起,我重写了上面的问题。

标签: python python-2.7 pyparsing


【解决方案1】:

正如哈里森所指出的,nltk 已命名实体识别,这正是您在这项任务中所需要的。 Here 是一个很好的示例,可以帮助您入门。

来自网站:

import nltk 

sentences = nltk.sent_tokenize(text)
tokenized_sentences =      [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)

def extract_entity_names(t):
    entity_names = []

    if hasattr(t, 'label') and t.label:
        if t.label() == 'NE':
            entity_names.append(' '.join([child[0] for child in t]))
        else:
            for child in t:
                entity_names.extend(extract_entity_names(child))

    return entity_names

entity_names = []
for tree in chunked_sentences:
    # Print results per sentence
    # print extract_entity_names(tree)

    entity_names.extend(extract_entity_names(tree))

# Print all entity names
#print entity_names

# Print unique entity names
print set(entity_names)

【讨论】:

  • 太棒了,这很有帮助,谢谢
【解决方案2】:

不太确定名称识别。但是,如果您知道要查找的名称,那将很容易。您可以列出所有要查找的名称,并检查每个名称是否都在字符串中,如果是,请使用string.replace。如果名称是随机的,您可以查看 NLTK,我认为它们可能具有一些名称实体识别。不过我真的什么都不知道……

但至于电话号码,这很简单。您可以将字符串拆分为列表并检查是否有任何元素由数字组成。您甚至可以检查长度以确保它是 10 位数字(根据您的示例,我假设所有数字都是 10)。

这样的……

example_input = 'Please call Robert on 0430013454 to discuss this further.'

new_list = example_input.split(' ')

for word in new_list:
    if word.isdigit():
        pos = new_list.index(word)
        new_list[pos] = 'PHONE'

example_output = ' '.join(new_list)

print example_output

这将是输出:'Please call Robert on PHONE to discuss this further'

如果您想确保数字的长度为 10,则 if 语句类似于 if word.isdigit() and len(word) == 10:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多