python: return 字典中值列表的精确匹配

python: return the exact match from list of values in a dictionary

我有一个字典如下:

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']

问题是当我 运行 函数时,它 return 所有可能的匹配项,但是我只希望它 return 匹配键值 'happen2'。所以所需的输出将是:

['happen2 to me this news on TV']

试试这个:

def replacer():
    my_words = my_string.split(" ")
    result = []
    for key, value in dictionary.items():
        for item in value:
            if item == my_words[0]:
                result.append(key + " to me " + " ".join(my_words[1:]))
    return result

这样做怎么样:-

def replacer(ms, md):
    tokens = ms.split()
    firstWord = tokens[0]
    for k, v in md.items():
        if firstWord in v:
            return k + ' ' + ' '.join(tokens[1:])

myString = 'happen this news on TV'
myDict = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}

print(replacer(myString, myDict))
def replacer(dictionary, string):
    replaced = []
    for key, val in dictionary.items():
        for v in val:
            if string.startswith(v):
                replaced.append(string.replace(v, key))
    return replaced

输出:

>>> 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'
>>> replacer(dictionary, my_string)
['happen2 this news on TV']