Reputation: 100
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 ?
Upvotes: 0
Views: 281
Reputation: 80
If what you mean is that the string "Triple" is to be treated as a keyword whose following string's value is to be replaced by itself tripled, then the following can accomplish what you want:
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])
To repeat the argument any number of times, a dictionary with different keywords and corresponding values could be used:
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])
Inputs:
1. Double x Triple y
2. Double Triple y
3. Triple x Double Double y Triple z Double
Outputs:
1. xx yyy
2. yyyyyy
3. xxx yyyy zzz Double
Note: this solution also has the effect of multiplying the value of repeated keywords. That is due to parsing the string in reverse.
Upvotes: 2