首页 > 解决方案 > 用于将串在一起的单词拆分为单个单词的 Python 函数

问题描述

我正在尝试想出一个函数,该函数需要像这样的条目

“企业标识符”、“名字”、“街道地址”

和输出

“企业标识符”、“名字”、“街道地址”

这似乎是一个涉及 NLP 的相当复杂的问题,因为该函数必须遍历一个字符串并针对一个词汇表进行测试,以查看它何时到达词汇表中的一个单词,但对于第一个示例,“businessidentifier”可能首先出现作为“总线标识符”。有没有人遇到过完成这项任务的功能?

标签: pythonnlp

解决方案


首先我们需要得到很多英文单词,我在这里使用了nltk。然后我将所有单词加载到 dict 中,以便所有以“a”开头的单词都在eng_dict键“a”下的 dict 中,以便更快地搜索单词。然后我按所有单词的长度对所有单词进行排序,这样当我们在句子中查找单词时,我们首先会尝试将其与最长的单词匹配,因此给定“businessidentifier”,我们将首先检查“business”而不是“bus” . 现在我们的单词格式很好,我们可以创建函数来匹配我们的句子和单词。在这里,我创建了循环函数,它尝试匹配以与句子相同的字母开头的所有单词,如果我们找到一个,则将其添加到我们的返回列表并循环查找下一个。

from nltk.corpus import words
word_list = words.words()

eng_dict = {chr(i): sorted([word for word in word_list if word[0] == chr(i)], key=len, reverse=True) for i in range(ord('a'), ord('z')+1)}

def split_into_words(x):
    ret = []
    for word in eng_dict[x[0]]:
        if x.startswith(word):
            ret.append(word)
            x = x[len(word):]
            break
    if len(x) != 0:
        ret.extend(split_into_words(x))
    return ret

raw_sentences = ["businessidentifier", "firstname", "streetaddress"]
finall_sentence = [split_into_words(i) for i in raw_sentences]

print(finall_sentence)

输出:

[['business', 'identifier'], ['first', 'name'], ['street', 'address']]

推荐阅读