gpt4 book ai didi

python - 如何在 python 中使用字典将多个单词替换为单个单词?

转载 作者:行者123 更新时间:2023-12-02 02:15:48 25 4
gpt4 key购买 nike

我有一个键和多个值的字典,如下所示:

word_list = {'cool':['better','good','best','great'], 'car':['vehicle','moving','automobile','four-wheeler'], 'sound':['noise', 'disturbance', 'rattle']}
sentences = ['that day I heard a vehicle noise not a great four-wheeler', 'the automobile industry is doing good these days', 'that moving noise is better now']

由于我有一个给定键的多个值,如果这些值中的任何一个出现在句子中,我想用其关联的键替换它们。

我尝试了以下方法,但没有得到想要的输出。

results= [' '.join(word_list.get(y, y) for y in w.split()) for w in sentences]

期望的输出:

['that day I heard a car sound not a cool car', 'the car industry is doing cool these days', 'that car sound is better now']

不确定如何实现。

最佳答案

技巧实际上是创建一个反向映射,您将其设置为键、替换键的每个值以及键的值。

然后就很简单了,因为你只需要遍历每个句子中的每个单词并将其替换为该倒置映射的值,如果该单词是此映射的键之一。

word_list = {
'cool': ['better','good','best','great'],
'car': ['vehicle','moving','automobile','four-wheeler'],
'sound': ['noise', 'disturbance', 'rattle']
}
sentences = [
'that day I heard a vehicle noise not a great four-wheeler',
'the automobile industry is doing good these days',
'that moving noise is better now'
]

swapped_word_list = {
word: replacement
for replacement, words in word_list.items()
for word in words
}
new_sentences = [
' '.join([
swapped_word_list.get(word, word)
for word in sentence.split()
])
for sentence in sentences
]

关于python - 如何在 python 中使用字典将多个单词替换为单个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67203694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com