首页 > 解决方案 > How to convert strings to abbreviations

问题描述

I want to do something like this if i have a textual transcript of a speech recognition system i want to convert this text like this - Triple A converts in AAA. Can someone help ?

标签: pythonmachine-learningnlptext-processing

解决方案


重复 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 Double


注意:此解决方案还具有将重复关键字的值相乘的效果。这是由于反向解析字符串。


推荐阅读