【问题标题】:Substitute substrings using a dictionary in Python [duplicate]在Python中使用字典替换子字符串[重复]
【发布时间】:2016-02-03 20:57:28
【问题描述】:

我有这个字符串

message = '10100010011'

还有这本词典

codes = {97: '1', 98: '01', 107: '001', 114: '000'}

我需要使用字典将原始消息替换为类似的内容

[97, 98, 114, 97, 107, 97]

我尝试了我自己的方法,这很有效,但是当我使用一些非常大的字符串时,它真的很慢。还有比这更快的方法吗?

    codes = dict(zip(codes.values(), codes.keys()))
    decoded_mess = []
    pom = ""
    for i in message:
        pom += i
        if pom in codes:
            decoded_mess.append(codes[pom])
            pom = ""

我在Easiest way to replace a string using a dictionary of replacements? 看到了答案,我试过了,但这对我不起作用。可能是因为他们处理的是整个单词,但我有 1 长串 1 和 0。

【问题讨论】:

  • 你的字典是不是弄错了?键(或值,目前)不应该都有固定的长度吗?
  • @jonrsharpe 他在解决方案中交换键值。
  • @MarounMaroun 哦...那为什么要单独显示呢?!
  • 鉴于当前的限制,您无法更有效地做到这一点。如果你有固定长度的键,那会更容易(因为你可以将字符串切成适当的长度来开始,而不是建立它直到匹配为止)。
  • @jonrsharpe 这些键(1、01、001、000)看起来可能是霍夫曼编码。

标签: python string dictionary substitution


【解决方案1】:

首先,codes 字典应该是向后的,以便于查找。我的策略是一次扫描一个字符的消息。如果找到替代品,请将其退回。如果没有,请添加下一个字符并再次查找。继续这样做,直到找到替换或消息用完为止。

def seach_replace(buffer, codes):
    codes = {v: k for k, v in codes.items()}  # Reverse the key, value
    text_so_far = ''
    for c in buffer:
        text_so_far += c
        if text_so_far in codes:
            yield codes[text_so_far]
            text_so_far = ''
    if text_so_far:
        yield text_so_far

if __name__ == '__main__':
    message = '10100010011'
    codes = {97: '1', 98: '01', 107: '001', 114: '000'}
    print(list(seach_replace(message, codes)))

输出:

[97, 98, 114, 97, 107, 97]

【讨论】:

  • any与OP的策略有何不同?除了使用生成器之类的语义之外?
  • @Shashank:生成器通过不创建累积列表来使用更少的内存。