gpt4 book ai didi

python - 正则表达式使用递增的数字序列 Python

转载 作者:太空狗 更新时间:2023-10-29 20:23:37 25 4
gpt4 key购买 nike

假设我有一个字符串:

teststring =  "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" 

我想要的是:

testlist = ["1.3 Hello how are you", "1.4 I am fine, thanks 1.2 Hi There", "1.5 Great!"]

基本上,仅在差异为 .1(即 1.2 到 1.3)的递增数字上拆分。

有没有办法用正则表达式拆分它,但只捕获递增的序列号?我用 Python 编写了代码,通过对每个代码使用自定义的 re.compile() 进行顺序迭代,这没问题,但非常笨拙。

像这样(其中 parts1_temp 是字符串中 x.x. 数字的给定列表):

parts1_temp = ['1.3','1.4','1.2','1.5']
parts_num = range(int(parts1_temp.split('.')[1]), int(parts1_temp.split('.')[1])+30)
parts_search = ['.'.join([parts1_temp.split('.')[0], str(parts_num_el)]) for parts_num_el in parts_num]
#parts_search should be ['1.3','1.4','1.5',...,'1.32']

for k in range(len(parts_search)-1):
rxtemp = re.compile(r"(?:"+str(parts_search[k])+")([\s\S]*?)(?=(?:"+str(parts_search[k+1])+"))", re.MULTILINE)
parts_fin = [match.group(0) for match in rxtemp.finditer(teststring)]

但是人是丑陋的。有没有办法在正则表达式中更直接地做到这一点?我想这是有人在某个时候想要使用正则表达式的功能,但我找不到任何关于如何解决这个问题的想法(也许纯正则表达式是不可能的)。

最佳答案

使用正则表达式来做这件事似乎过于复杂。这个处理怎么样:

import re

teststring = "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!"
res = []
expected = None
for s in re.findall(r'\d+(?:\.\d+)?|\D+', teststring):
if s[0].isdigit() and expected is None:
expected = s
fmt = '{0:.' + str(max(0, len(s) - (s+'.').find('.') - 1)) + 'f}'
inc = float(re.sub(r'\d', '0', s)[0:-1] + '1')
if s == expected:
res.append(s)
expected = fmt.format(float(s) + inc)
elif expected:
res[-1] = res[-1] + s

print (res)

如果数字恰好有 2 位小数或更多,或者没有,这也适用。

关于python - 正则表达式使用递增的数字序列 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com