【问题标题】:fix length re.sub with dictionary用字典修复长度 re.sub
【发布时间】:2013-10-05 01:39:32
【问题描述】:

我有一本字典,所有键都是三个字母长:threeLetterDict={'abc': 'foo', 'def': 'bar', 'ghi': 'ha' ...}

现在我需要将句子abcdefghi 翻译成foobarha。我正在使用re.sub 尝试以下方法,但不知道如何将字典放入其中:

p = re.compile('.{3}') # match every three letters
re.sub(p,'how to put dictionary here?', "abcdefghi")

谢谢! (无需检查输入长度是否为三的倍数)

【问题讨论】:

    标签: python regex dictionary


    【解决方案1】:

    您可以将任何可调用对象传递给re.sub,因此:

    p.sub(lambda m: threeLetterDict[m.group(0)], "abcdefghi")
    

    It works!

    【讨论】:

    • 我不熟悉 python 和 lambda,你能解释一下这是做什么的吗? lambda m: threeLetterDict[m.group(0)] 非常感谢!
    • @Arch1tect: lambda argument: some expression 几乎等同于定义一个函数 def func(argument): return some expression 然后在使用 lambda 的任何地方使用它。也就是说,它是一个内联函数。我希望这是有道理的:D
    • re.sub 需要 3 个参数,对吗?不需要传入p 吗?
    • @Arch1tect:这是re.sub 的模块级版本,它采用未编译的正则表达式(作为字符串)。您已经编译了一个正则表达式,因此要利用它,您可以在正则表达式对象上调用 sub。见help(re.compile(""))
    • 当字符串中有一个不在字典中的三个字母时,它会给出错误,因为它不是键...如何在 lambda 中添加 if 语句以防止在找不到时替换在字典里?谢谢!
    【解决方案2】:

    完全避免re 的解决方案:

    threeLetterDict={'abc': 'foo', 'def': 'bar', 'ghi': 'ha'}
    
    threes = map("".join, zip(*[iter('abcdefghi')]*3))
    
    "".join(threeLetterDict[three] for three in threes)
    #>>> 'foobarha'
    

    【讨论】:

      【解决方案3】:

      你可能不需要在这里使用 sub:

      >>> p = re.compile('.{3}')
      >>> ''.join([threeLetterDict.get(i, i) for i in p.findall('abcdefghi')])
      'foobarha'
      

      只是一个替代解决方案:)。

      【讨论】:

        猜你喜欢
        • 2018-09-11
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        • 2022-12-28
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多