【问题标题】:List comprehension to replace values in a string with key strings from a dictionary列表理解用字典中的键字符串替换字符串中的值
【发布时间】:2021-01-02 18:47:37
【问题描述】:

寻求一些帮助。 此功能将缩写词替换为标准拼写。我正在尝试用列表理解替换第 3-6 行。我试过这个:

words[i] = [key for i, word in enumerate(words) for key, value in abbrevs.items()
            if word == abbrevs[key]] 

def text_deciphered(text_message, abbrevs):
    words = text_message.split()
    for i, word in enumerate(words):
        for key in abbrevs.keys():
            if word == abbrevs[key]:
                words[i] = key    
    words = ' '.join(words)
    return words

text_message = "Hey, wat r our plans for tn"
abbrevs = {"what": "wat", "are": "r", "tonight": "tn"}
print(text_deciphered(text_message, abbrevs))

但它只返回缩写形式的键 - 今晚是什么

【问题讨论】:

    标签: python list loops nested list-comprehension


    【解决方案1】:

    首先,字典背后的想法是根据键查找值,而不是相反。这保证了即时查找,而不是像您正在做的那样转储所有条目并逐个查看它们。首先反转您的字典:abbrevs = {v: k for k, v in abbrevs.items()} 或在继续之前从一开始就正确构建它。

    调整后,这可以是使用列表理解和dict.get(element, element) 的简单单行代码。如果element 不在字典中,则回退值为element 本身:

    >>> text_message = "Hey, wat r our plans for tn"
    >>> abbrevs = {"wat": "what", "r": "are", "tn": "tonight"}
    >>> " ".join([abbrevs.get(x, x) for x in text_message.split()])
    'Hey, what are our plans for tonight'
    

    所以你的功能是:

    def text_deciphered(text_message, abbrevs):
        return " ".join([abbrevs.get(x, x) for x in text_message.split()])
    

    请注意,split 等同于 \s+,因此您可能会在不经意间挤压空格。我更喜欢使用 re.sub 和 lambda 来应用于每个单词:

    >>> import re
    >>> text_message = "Hey,   wat   r our plans for tn"
    >>> abbrevs = {"wat": "what", "r": "are", "tn": "tonight"}
    >>> re.sub(r"(\w+)", lambda x: abbrevs.get(x.group(), x.group()), text_message)
    'Hey,   what   are our plans for tonight'
    

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2022-01-15
      • 1970-01-01
      • 2017-08-24
      • 2018-03-02
      • 1970-01-01
      • 2013-05-01
      • 2021-05-22
      • 2017-07-15
      相关资源
      最近更新 更多