我想实现这样的功能:如果我有一个语音识别系统的文本记录,我想将这样的文本转换为缩写形式——例如,”Triple A”转换为”AAA”。有人能帮我吗?
回答:
重复三次
如果你的意思是将字符串”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. Double x Triple y
2. Double Triple y
3. Triple x Double Double y Triple z Double
输出:
1. xx yyy
2. yyyyyy
3. xxx yyyy zzz Double
注意:这个解决方案还有一个效果,即重复关键字的值会增加。这是由于反向解析字符串造成的。