我有一本字典如下:
dictionary = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}
我有一个字符串如下
my_string = 'happen this news on TV'
但我想做的是找到字符串的第一个单词与字典中的值的精确匹配,然后用相应的键替换它
def replacer():
result = []
for key,val in dictionary.items():
if any(my_string.split(' ', 1)[0] in s for s in val):
done= my_string.split(' ', 1)[0].replace(val, key.split(' ', 1)[0]) + ' to me' + ' ' + ' '.join(my_string.split()[1:])
result.append(done)
return result
电流输出:
['happen to me this news on TV', 'happen2 to me this news on TV', 'happen to me this news on TV', 'happen to me this news on TV', 'happen to me this news on TV']
问题是,当我运行该函数时,它返回所有可能的匹配项,但是我只希望它返回与键'happen2'的值匹配的项。因此,期望的输出是:
['happen2 to me this news on TV']
输出:
这样做怎么样
试试这个:
相关问题 更多 >
编程相关推荐