如何将字符串转换为缩写

How to convert strings to abbreviations

如果我有语音识别系统的文本抄本,我想做这样的事情我想像这样转换此文本 - AAA 中的 Triple A 转换。有人可以帮忙吗?

重复3次

如果你的意思是把字符串"Triple"当作一个关键字,其后面的字符串的值要被自身替换成原来的三倍,那么下面就可以实现你想要的:

def tripler(s):
    triples = 0
    s = [ss.strip() for ss in s.split()][::-1]

    for i in range(len(s) - 1):
        if s[i - triples + 1] == 'Triple':
            s[i - triples] *= 3

            del s[i - triples + 1]
            triples += 1

    return ' '.join(s[::-1])

动态重复

要多次重复参数,可以使用具有不同关键字和对应值的字典:

repeat_keywords = {'Double':2, 'Triple':3}

def repeater(s):
    repeats = 0
    s = [ss.strip() for ss in s.split()][::-1]

    for i in range(len(s) - 1):
        if s[i - repeats + 1] in repeat_keywords:
            s[i - repeats] *= repeat_keywords[s[i - repeats + 1]]

            del s[i - repeats + 1]
            repeats += 1

    return ' '.join(s[::-1])

输入:
1. 双 x 三 y
2.双三y
3. 三倍 x 双倍 y 三倍 z 双倍

输出:
1. xx yyy
2. yyyyyy
3. xxx yyyy zzz 双


注意:该方案还有对重复关键字的价值成倍增加的效果。这是由于反向解析字符串。