可选地替换子字符串 python [英] Optionally replacing a substring python

查看:48
本文介绍了可选地替换子字符串 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的替换清单格式如下.

My list of replacement is in the following format.

lstrep = [('A',('aa','aA','Aa','AA')),('I',('ii','iI','Ii','II')),.....]

我想要实现的是通过所有可能的替换来选择性地更改字母的出现.输入词也应该是列表的成员.例如

What I want to achieve is optionally change the occurrence of the letter by all the possible replacements. The input word should also be a member of the list. e.g.

输入 - DArA

预期输出 -

['DArA','DaarA','Daaraa','DAraa','DaArA','DAraA','DaAraA','DAarA','DAarAa', 'DArAa','DAArA','DAArAA','DArAA']

我的尝试是

lstrep = [('A',('aa','aA','Aa','AA'))]
def alte(word,lstrep):
    output = [word]
    for (a,b) in lstrep:
        for bb in b:
            output.append(word.replace(a,bb))
    return output
print alte('DArA',lstrep)

我收到的输出是 ['DAarA', 'Daaraa', 'DaAraA', 'DAarAa', 'DAArAA'] 即所有出现的 'A' 都被替换为 'aa',分别为aA"、Aa"和AA".我想要的是它应该提供可选替换的所有排列.

The output I received was ['DArA', 'Daaraa', 'DaAraA', 'DAarAa', 'DAArAA'] i.e. All occurrences of 'A' were replaced by 'aa','aA','Aa' and 'AA' respectively. What I want is that it should give all permutations of optional replacements.

推荐答案

itertools.product 将给出所有的排列.您可以建立一个替换列表,然后让它处理排列.

itertools.product will give all of the permutations. You can build up a list of substitutions and then let it handle the permutations.

import itertools

lstrep = [('A',('aa','aA','Aa','AA')),('I',('ii','iI','Ii','II'))]
input_str = 'DArA'

# make substitution list a dict for easy lookup
lstrep_map = dict(lstrep)

# a substitution is an index plus a string to substitute. build
# list of subs [[(index1, sub1), (index1, sub2)], ...] for all
# characters in lstrep_map.
subs = []
for i, c in enumerate(input_str):
    if c in lstrep_map:
        subs.append([(i, sub) for sub in lstrep_map[c]])

# build output by applying each sub recorded
out = [input_str]
for sub in itertools.product(*subs):
    # make input a list for easy substitution
    input_list = list(input_str)
    for i, cc in sub:
        input_list[i] = cc
    out.append(''.join(input_list))

print(out)

这篇关于可选地替换子字符串 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆