使用Python中的字典替换子字符串

时间:2015-11-03 16:02:00

标签: python string dictionary substitution

我有这个字符串

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和0。

1 个答案:

答案 0 :(得分:-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]