【问题标题】:replace more than 1 word that has same meanings without adding 1 by 1替换超过 1 个具有相同含义的单词而不用 1 加 1
【发布时间】:2021-08-16 11:50:53
【问题描述】:

关于我的问题 Replace word, but another word with same letter format got replaced

def slangwords(kalimat):
    replacements = {
        'sweets': 'candy',
        'sweetmeat': 'candy',
        'jawbreaker': 'candy'
     }
    words = kalimat.split(' ')
    for i, word in enumerate(words):
        words[i] = replacements.get(word, word)
    return " ".join(words)

有没有我可以替换超过 1 个具有相同含义的单词而不用 1 加 1。所需的输出是这样实现的,只是输入所有这些糖果表示效率不高

'sweets': 'candy',
'sweetmeat': 'candy',
'jawbreaker': 'candy'

【问题讨论】:

  • 你想改哪些字,请说明你想做什么?
  • 请同时添加您的示例输入和预期输出。
  • 使用理解" ".join(replacements.get(word, word) for word in words)
  • 您可以随心所欲地存储它,但为了替换,您需要以您当前拥有的格式进行处理。
  • @TimRoberts 好的,所以如果不输入所有这些糖果表示,我就无法做到这一点,对吧? 'sweets': ** candy**

标签: python replace


【解决方案1】:
def slangwords(kalimat):
    replacements = ['sweets', 'sweetmeat', 'jawbreaker']
    words = kalimat.split(' ')
    for i, word in enumerate(words):
        if word in replacements:
            words[i] = 'candy'
    return " ".join(words)

或者你可以只使用生成器理解。

def slangwords(kalimat):
    replacements = ['sweets', 'sweetmeat', 'jawbreaker']
    words = kalimat.split(' ')
    return " ".join('candy' if w in replacements else w for w in words)

如果你喜欢正则表达式。

import re
def slangwords(kalimat):
    candies = re.compile(r'\b(sweets|sweetmeat|jawbreaker)\b')
    return candies.sub('candy', kalimat)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2013-05-26
    • 2019-06-15
    相关资源
    最近更新 更多