python - 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 ?
解决方案
重复 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
注意:此解决方案还具有将重复关键字的值相乘的效果。这是由于反向解析字符串。
推荐阅读
- c++ - QSqlQuery 没有从 postgresql 中选择记录
- node.js - 猫鼬:按名称查找模型 - 回调从未调用
- windows - 替换 Path 变量中的值
- twilio - 我想用简单的文本回复 twilio SMS,同时将 SMS 转发到某个 emailId
- javascript - 在 javascript 中添加日期并产生意外结果
- java - 如何以编程方式滚动到 Java 桌面应用程序部分的特定部分
- android - 以编程方式转换 .jks 文件
- php - 将所有重复出现的字符串替换为单个相同的字符串
- php - 如果 php fileinfo 扩展名不被允许并且不能在共享服务器上允许,则 laravel 文件上传
- node.js - npm audit 仅适用于生产依赖项?