python - 用于将串在一起的单词拆分为单个单词的 Python 函数
问题描述
我正在尝试想出一个函数,该函数需要像这样的条目
“企业标识符”、“名字”、“街道地址”
和输出
“企业标识符”、“名字”、“街道地址”
这似乎是一个涉及 NLP 的相当复杂的问题,因为该函数必须遍历一个字符串并针对一个词汇表进行测试,以查看它何时到达词汇表中的一个单词,但对于第一个示例,“businessidentifier”可能首先出现作为“总线标识符”。有没有人遇到过完成这项任务的功能?
解决方案
首先我们需要得到很多英文单词,我在这里使用了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']]
推荐阅读
- python - 如何通过登录 Seaborn 等量缩放 x 和 y 轴?
- c# - 正则表达式模式不在 c# 中工作,但在在线正则表达式测试器中工作
- .htaccess - .htaccess 将 example.com 重定向到 example.com/admin_panel
- html - CSS 边框半径仅围绕模态 div 窗口的一个角
- angularjs - AngularUI Calendar 获取事件对象后获取范围
- javascript - 如何在 React JSX 中映射包含 JSON 对象的数组?
- css - 是否可以在内联 svg 中使用 css 变量?
- firebase - 在 Ionic App 中使用 firebase 匿名身份验证是否安全?
- c# - 从 PictureBox 保存原始图像,不调整大小
- wordpress - 如何在新编辑器(古腾堡)的画廊块中将默认“链接”属性设置为“媒体”