python:从字典中的值列表中返回精确匹配

2024-06-26 14:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下:

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

Tags: toinstring字典onmyvalresult
6条回答
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']

这样做怎么样

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():
    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

相关问题 更多 >