如何将字符串中的多个字符更有效地映射到单个字符?

时间:2019-03-06 08:40:15

标签: python python-3.x string dictionary replace

我正在寻找一种更有效的方式来将字符串中的多个字符替换为单个字符。

当前,我的代码类似于以下内容:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

output = ''
for char in example:
    if char in VOWELS:
        output += 'v'
    elif char in VOWELS.upper():
        output += 'V'
    elif char in CONSONANTS:
        ....

最终,在示例中,它将返回Vccvcvcvcvvc

我想提高效率的部分是:

for char in example:
    if char in VOWELS:
        output += 'v'
    elif char in VOWELS.upper():
        output += 'V'
    elif char in CONSONANTS:
        ....

理想地,该解决方案将允许将字符字典映射为键,其值是选项列表。例如

replace_dict = {'v': VOWELS,
                'V': VOWELS.upper(),
                'c': CONSONANTS,
                ...

不幸的是,我对map不太熟悉,但是我希望解决方案能以某种方式加以利用。

研究

我发现了类似的问题:python replace multiple characters in a string

这表明我将必须执行以下操作:

target = 'Accomodation'
charset = 'aeioubcdfghjklmnpqrstvwxyzAEIOUBCDFGHJKLMNPQRSTVWXYZ'
key = 'vvvvvcccccccccccccccccccccVVVVVCCCCCCCCCCCCCCCCCCCCC'

对我来说,问题是,尽管分配节省了if / else语句块,但分配看起来并不特别清楚。另外,如果我想添加更多的字符集,则分配的可读性将越来越低,例如用于不同的外来字符集。


也许对内置函数有较广知识的人能提供一个比上述两个示例更有效/更干净地工作的示例吗?

我也欢迎其他不需要字典的想法。

解决方案应位于python3中。

6 个答案:

答案 0 :(得分:3)

创建这样的字典有更有效的方法:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

replace_dict = {
    **{v: 'v' for v in VOWELS},
    **{V: 'V' for V in VOWELS.upper()},
    **{c: 'c' for c in CONSONANTS}
}

print(''.join(replace_dict[s] for s in example))

# Vccvcvcvcvvc

答案 1 :(得分:2)

这是使用var deadline = new Date("mar 6, 2019 09:12:25").getTime(); 的一种方法。

例如:

dict

输出:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

replace_dict = {'v': VOWELS,
                "V": VOWELS.upper(),
                "c": CONSONANTS
                }


print("".join(k for i in example 
              for k, v in replace_dict.items() if i in v
              )
        )

答案 2 :(得分:2)

您的replace_dict想法很接近,但是最好将dict“由内而外”翻转,即将其从{'v': 'aei', 'c': 'bc'}变成{'a': 'v', 'e': 'v', 'b': 'c', ...}

def get_replace_map_from_dict(replace_dict):
    replace_map = {}
    for cls, chars in replace_dict.items():
        replace_map.update(dict.fromkeys(chars, cls))
    return replace_map


def replace_with_map(s, replace_map):
    return "".join(replace_map.get(c, c) for c in s)


VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"


replace_map = get_replace_map_from_dict(
    {"v": VOWELS, "V": VOWELS.upper(), "c": CONSONANTS}
)
print(replace_with_map("Accommodation, thanks!", replace_map))

上面的replace_with_map函数保留所有未映射的字符(但是您可以在其中使用第二个参数将其更改为.get()),因此输出为

  

Vccvccvcvcvvc,ccvccc!

答案 3 :(得分:2)

如何反向查找正在执行的操作-应该是可扩展的

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
example = "Accomodation"
lookup_dict = {k: "v" for k in VOWELS}
lookup_dict.update({k: "c" for k in CONSONANTS})
lookup_dict.update({k: "V" for k in VOWELS.upper()})
lookup_dict.update({k: "C" for k in CONSONANTS.upper()})
''.join([lookup_dict[i] for i in example])

答案 4 :(得分:1)

尝试这个。不需要辅音,不仅可以使用英语,而且还可以使用俄语字母(我很惊讶):

example = 'AccomodatioNеёэыуюяЕЁЭЫуюяРаботает'
VOWELS = 'aeiouуаоиеёэыуюя'

output = ''
for char in example:
    if char.isalpha():
        x = 'v' if char.lower() in VOWELS else 'c'
        output += x if char.islower() else x.upper()

print(output)
  

VccvcvcvcvvCvvvvvvvVVVvvvCvcvcvvc

答案 5 :(得分:1)

我是Python的新手,并且玩起来很有趣。让我们看看这些词典有多好。这里提出了四种算法:

  1. Alex(我自己)-C运行时库样式
  2. Adam-与四个字符串匹配
  3. Sanyash,Rakesh,Mortz-字典(查找表格)
  4. AKX-替换为地图

我对建议的代码进行了一些小的更正,以使所有工作保持一致。另外,我想将合并的代码保持在100行以下,但是使用四个功能测试到127个并尝试用额外的空行数来满足PyCharm。这是第一场比赛的结果:

Place  Name Time   Total
1.      AKX 0.6777 16.5018 The winner of Gold medal!!!
2.  Sanyash 0.8874 21.5725 Slower by 31%
3.     Alex 0.9573 23.2569 Slower by 41%
4.     Adam 0.9584 23.2210 Slower by 41%

然后,我对代码做了一些小的改进:

VOWELS_UP = VOWELS.upper()

def vowels_consonants0(example):
    output = ''
    for char in example:
        if char.isalpha():
            if char.islower():
                output += 'v' if char in VOWELS else 'c'
            else:
                output += 'V' if char in VOWELS_UP else 'C'
    return output

那让我排名第二:

Place  Name Time   Total

1.      AKX 0.6825 16.5331 The winner of Gold medal!!!
2.     Alex 0.7026 17.1036 Slower by  3%
3.  Sanyash 0.8557 20.8817 Slower by 25%
4.     Adam 0.9631 23.3327 Slower by 41%

现在我需要将这3%剃光并获得第一名。我用列夫·托尔斯泰小说War and Peace

的文字进行了测试

原始源代码:

import time
import itertools

VOWELS = 'eaiouу'  # in order of letter frequency
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'


def vowels_consonants0(example):
    output = ''
    for char in example:
        if char.isalpha():
            x = 'v' if char.lower() in VOWELS else 'c'
            output += x if char.islower() else x.upper()
    return output


def vowels_consonants1(example):
    output = ''
    for char in example:
        if char in VOWELS:
            output += 'v'
        elif char in VOWELS.upper():
            output += 'V'
        elif char in CONSONANTS:
            output += 'c'
        elif char in CONSONANTS.upper():
            output += 'C'
    return output


def vowels_consonants2(example):
    replace_dict = {
        **{v: 'v' for v in VOWELS},
        **{V: 'V' for V in VOWELS.upper()},
        **{c: 'c' for c in CONSONANTS},
        **{c: 'c' for c in CONSONANTS.upper()}
    }
    return ''.join(replace_dict[s] if s in replace_dict else '' for s in example)


def get_replace_map_from_dict(replace_dict):
    replace_map = {}
    for cls, chars in replace_dict.items():
        replace_map.update(dict.fromkeys(chars, cls))
    return replace_map


def replace_with_map(s, replace_map):
    return "".join(replace_map.get(c, c) for c in s)


replace_map = get_replace_map_from_dict(
    {"v": VOWELS, "V": VOWELS.upper(), "c": CONSONANTS, "C": CONSONANTS.upper()}
)


def vowels_consonants3(example):
    output = ''
    for char in example:
        if char in replace_map:
            output += char
    output = replace_with_map(output, replace_map)
    return output


def test(function, name):
    text = open(name, encoding='utf-8')
    t0 = time.perf_counter()
    line_number = 0
    char_number = 0
    vc_number = 0  # vowels and consonants
    while True:
        line_number += 1
        line = text.readline()
        if not line:
            break
        char_number += len(line)
        vc_line = function(line)
        vc_number += len(vc_line)
    t0 = time.perf_counter() - t0
    text.close()
    return t0, line_number, char_number, vc_number


tests = [vowels_consonants0, vowels_consonants1, vowels_consonants2, vowels_consonants3]
names = ["Alex", "Adam", "Sanyash", "AKX"]
best_time = float('inf')
run_times = [best_time for _ in tests]
sum_times = [0.0 for _ in tests]
show_result = [True for _ in tests]

print("\n!!! Start the race by permutation with no repetitions now ...\n")
print("  * - best time in race so far")
print("  + - personal best time\n")
print("Note  Name Time (Permutation)")

products = itertools.permutations([0, 1, 2, 3])

for p in list(products):
    print(p)
    for n in p:
        clock, lines, chars, vcs = test(tests[n], 'war_peace.txt')
        sum_times[n] += clock
        note = " "
        if clock < run_times[n]:
            run_times[n] = clock
            note = "+"  # Improved personal best time
        if clock < best_time:
            best_time = clock
            note = "*"  # Improved total best time
        print("%s %8s %6.4f" % (note, names[n], clock), end="")
        if show_result[n]:
            show_result[n] = False
            print("  Lines:", lines, "Characters:", chars, "Letters:", vcs)
        else:
            print()
print("\n!!! Finish !!! and the winner by the best run time is ...\n")
print("Place  Name Time   Total")
i = 0
for n in sorted(range(len(run_times)), key=run_times.__getitem__):
    i += 1
    t = run_times[n]
    print("%d. %8s %.4f %.4f " % (i, names[n], t, sum_times[n]), end="")
    if i == 1:
        print("The winner of Gold medal!!!")
    else:
        print("Slower by %2d%%" % (round(100.0 * (t - best_time)/best_time)))