python - 用顺序名称替换字符串?
问题描述
我想做的事情比解释更容易出现。假设我有一个这样的字符串:
The ^APPLE is a ^FRUIT
使用正则表达式 re.sub(),我想得到这个:
The ^V1 is a ^V2
看看它们是如何递增的。但现在更难的情况来了:
The ^X is ^Y but ^X is not ^Z
应该翻译成这样:
The ^V1 is ^V2 but ^V1 is not ^V3
即,如果它重复,那么它会保留替换,即 ^X => ^V1 情况。
我听说替换可以是一个函数,但不能正确。
https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem
解决方案
IIUC,你不需要re
。字符串操作将完成这项工作:
from collections import defaultdict
def sequential(str_):
d = defaultdict(int)
tokens = str_.split()
for i in tokens:
if i.startswith('^') and i not in d:
d[i] = '^V%s' % str(len(d) + 1)
return ' '.join(d.get(i, i) for i in tokens)
输出:
sequential('The ^APPLE is a ^FRUIT')
# 'The ^V1 is a ^V2'
sequential('The ^X is ^Y but ^X is not ^Z')
# 'The ^V1 is ^V2 but ^V1 is not ^V3'
推荐阅读
- r - 错误:无法使用 ggplot 将类型“环境”强制转换为“字符”类型的向量
- sql - 转换为相关子查询
- django - Django:检查列表中的值
- c++ - 在 Ubuntu 上的 Visual Studio 代码中编译 C++
- node.js - 如何将 midi 文件作为消息附件发送
- python-2.7 - 指定存放上传图片的目录
- c++ - 车身角度不变 box2D C++
- javascript - 找到一个值下的最大属性
- javascript - 如何更改 iframe src 中的 DOM 元素(背景颜色)?
- javascript - 以覆盖模式从剪贴板粘贴 - 输入光标移动到文本节点的末尾