我有一个看起来像这样的 Python 字符串:
"5 pounds cauliflower,
cut into 1-inch florets (about 18 cups)
2 large leeks,
1 teaspoons salt
3 cups of milk"
我需要为出现在关键字 cup 之前的每个数字加 1。
结果需要是:
"5 pounds cauliflower,
cut into 1-inch florets (about 19 cups)
2 large leeks,
1 teaspoons salt
4 cups of milk"
我有一些类似的东西:
import re
p = re.compile('([0-9]+) cup')
for i in p.finditer(s):
# do something with int(i.group(1)) + 1
我不知道如何只替换我在每次迭代中找到的数字。
我还有一个极端情况,我可能需要用 10 替换 9,所以我不能简单地获取数字的索引并将该数字替换为新数字,因为新数字可能更长。
也欢迎不涉及正则表达式的解决方案。
请您参考如下方法:
您可以将函数作为替换字符串传递给 sub 函数。此函数接收 match object作为论据。
处理接收到的参数以创建每个匹配项的替换字符串。
感谢@ctwheels 的回答,我改进了初始正则表达式处理。
mystring = """
5 pounds cauliflower,
cut into 1-inch florets (about 19 cups)
2 large leeks,
1 teaspoons salt
4 cups of milk
"""
p = r'\d+(?= +cups?\b)'
newstring = re.sub(p, lambda x: str(int(x.group(0))+1), mystring)
print(newstring)
# outputs:
5 pounds cauliflower,
cut into 1-inch florets (about 20 cups)
2 large leeks,
1 teaspoons salt
5 cups of milk
为了处理单词复数化(正如@CasimiretHippolyte 所要求的),我们可以使用更广泛的模式,但使用稍微复杂一些的替换函数:
def repl(x):
d = int(x.group(0).split()[0]) + 1
return str(d) + ' cup' if d == 1 else str(d) + ' cups'
p = r'\d+ cups?'
mystring = """
5 pounds cauliflower,
cut into 1-inch florets (about 19 cups)
2 large leeks,
1 teaspoons salt
4 cups of milk
1 cup of butter
0 cups of sugar"""
newstring = re.sub(p, repl, mystring)
print(newstring)
# outputs
5 pounds cauliflower,
cut into 1-inch florets (about 20 cups)
2 large leeks,
1 teaspoons salt
5 cups of milk
2 cups of butter
1 cup of sugar
