我正在寻找一个原生python解决方案,它允许我在字符串列表中的任何地方替换短语。基本上,这看起来是:
text_array = ['the store has a piano','dulcimer players are popular with the ladies','guitar','rock legends dont shy away from this gibson model or this PRS electric','guitar','fender guitar','PRS electric',...]我的目标是在text_array中找到短语(准确地),并将它们替换为我在调用thesaurus的dict中映射的字符串逻辑
thesaurus = {'gibson model':'guitar', 'fender guitar':'guitar', 'PRS electric':'guitar'}问题
我将如何迭代text_array的每个元素,并替换所有出现在thesaurus中标记的短语的地方?(注:我只想替换精确的匹配,并保留其余的字符串在-tact中)。
期望产出:
text_array = ['the store has a piano','dulcimer players are popular with the ladies','guitar','rock legends dont shy away from this guitar or this guitar', 'guitar','guitar','guitar']发布于 2022-01-27 07:38:12
这将是我的方法。这个不影响原始的text_array。
text_array = ['the store has a piano','dulcimer players are popular with the ladies','guitar','rock legends dont shy away from this gibson model or this PRS electric','guitar','fender guitar','PRS electric']
thesaurus = {'gibson model':'guitar', 'fender guitar':'guitar', 'PRS electric':'guitar'}
res = []
for text in text_array:
for key in thesaurus:
text = text.replace(key, thesaurus[key])
res.append(text)
print(res)发布于 2022-01-27 07:29:45
您可以使用下面的代码片段来获得预期的输出:
text_array = ['the store has a piano','dulcimer players are popular with the ladies','guitar','rock legends dont shy away from this gibson model or this PRS electric','guitar','fender guitar','PRS electric',...]
thesaurus = {'gibson model':'guitar', 'fender guitar':'guitar', 'PRS electric':'guitar'}
for index, val in enumerate(text_array):
# Checking if key exist in list item
for key in list(thesaurus.keys()):
if key in val:
# Updating List item value
text_array[index] = text_array[index].replace(key, thesaurus[key])发布于 2022-01-27 07:32:47
使用此代码
text_array = ['the store has a piano','dulcimer players are popular with the ladies','guitar','rock legends dont shy away from this gibson model or this PRS electric','guitar','fender guitar','PRS electric']
thesaurus = {'gibson model':'guitar', 'fender guitar':'guitar', 'PRS electric':'guitar'}
for key in thesaurus.keys():
for i,item in enumerate(text_array):
text_array[i]=item.replace(key,thesaurus[key])
print(text_array)结果:
['the store has a piano', 'dulcimer players are popular with the ladies', 'guitar', 'rock legends dont shy away from this guitar or this guitar', 'guitar', 'guitar', 'guitar']https://stackoverflow.com/questions/70874517
复制相似问题