【问题标题】:How to convert strings to abbreviations如何将字符串转换为缩写
【发布时间】:2020-02-19 23:56:00
【问题描述】:

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

【问题讨论】:

  • 可以做一个简单的查找和替换:s/Triple A/AAA/g

标签: python machine-learning nlp text-processing


【解决方案1】:

重复 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. Double Triple y
3. Triple x Double Double y Triple z Double

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


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

【讨论】:

  • 是的,我就是这样做的,但是五个 a ,两个 a 等等呢?
  • 意味着我必须为所有可能的情况创建单独的函数?
  • 我编辑了答案以包含动态重复数字。
  • 它输出与我在输入三元组中给出的相同字符串(“Triple A”)输出“Triple A”
  • @EshanAgarwal 从 cmets 和 post 来看,这是您问题的解决方案。花点时间阅读stackoverflow.com/help/someone-answers 并考虑接受/支持答案。
猜你喜欢
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 2021-06-11
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多