python - 使用字典替换句子中的单词

标签 python

我创建了一本字典,用来将各种单词转化为其基本形式。

dictionary = {'sunny': 'sun', 'banking': 'bank'}

def stemmingWords(sentence, dictionary):
    for word in sentence.split():
        temp = []
        if word in dictionary:
            word = dictionary[word]
            temp.append(word)
    sentence = ' '.join(temp)
    return(sentence)

现在,如果打印单独的单词,它似乎可以工作。然而,当我插入整个句子并且我想要该句子的更新版本时,似乎出了问题。例如,如果我这样做:

sentence = "the sun us shining"
new_sentence = stemmingWords(sentence, dictionary)
print(new_sentence)

给我“闪耀”。当我看着“阳光明媚的时候”。

对这里出了什么问题有什么想法吗?

最佳答案

首先,你的字典方向不对,把它倒过来

dictionary = {'sunny': 'sun', 'banking': 'bank'}

避免重新输入的简单方法是:

dictionary = {v:k for k,v in dictionary.items()}

请注意,如果多个单词与同一个单词匹配,则恢复字典将不起作用,您必须首先解决歧义:因此手动:

dictionary = {'sun', 'sunny': , 'sunn' : 'sunny', 'bank': 'banking'}

然后使用列表理解和 get 访问来分割并重建字符串,如果字典中没有,则返回原始值

def stemmingWords(sentence,dictionary):
    return " ".join([dictionary.get(w,w) for w in sentence.split()])

print(stemmingWords("the sun is shining",dictionary))

结果:

the sunny is shining

注意使用join时有意的([])。在这种情况下,显式传递列表推导式比生成器更快。

关于python - 使用字典替换句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918877/

相关文章:

来自一组png图像的python imageio mp4视频

python - 合并 2 个字幕 block 时遇到问题

python - 在 Python 行中查找多位整数

python - 扩展 Python 记录器

python - 从 bash 脚本中欺骗 python 的 os.isatty

python - Jupyter 笔记本 : Print Pandas Dataframe without wrapping on a new line (print statement is in external function)

python - 带变量和方法的下划线与双下划线

python - Django:我可以重定向点击/admin/的未经身份验证的用户吗

python - Mongoengine + Django : strange errors with fields during rendering

python - 在 Numpy 上优化向量归一化