我有一堆数字ID,我需要用新的数字ID编号
id="12.03"
id="23.343.Fdf--"
id="12-B.fdas7232"
id="12."
id="1."
id="1.-2"
id="2.02-R.-vdfs--erev-j"
id="48-34JJf"
id="5.01-G.f"
使用这个正则表达式:
id="[1-9]\d*(\.\d+)?
https://regexr.com/点,I am able to get the correct matches点.
然而,当我运行python脚本时,我认为这与捕获返回太多值的组有关.
以下是打印输出的两个示例:
('id="5.01","id=",'5.01','0.01')
我不知道如何阻止它返回上述两个示例中的第四个值".01"或"".
我得到这个错误:too many values to unpack (expected 3)
我try 了几种不同的正则表达式变体,试图让它返回单个字符串,比如添加额外的括号,^和$来标记字符串的开头和结尾,等等.
PID_REPLACEMENTS = {
"48":'9',
"23.343":'8',
"12.03":'7',
"12":'6',
"5.01":'5',
"2.02":'4',
"1":'3.08'}
my_text = substitute_oldid_index(my_text)
def substitute_oldid_index(my_text):
return substitute_newid(r"""((?P<pre> id=")(?P<post>[1-9]\d*(\.\d+)?))""", my_text)
def substitute_newid (findallnewid_regex, my_text):
data_oldids = re.findall(findallnewid_regex, my_text, re.I)
print(data_oldids)
for combined, pre, post in data_oldids:
if post.title() not in PID_REPLACEMENTS:
continue
my_text = re.sub(combined, "{}{}".format(pre, PID_REPLACEMENTS[post.title()]), my_text)
return my_text
有没有更好的方法来查找数字ID(可能包含小数点和其他句点,或者后面应该保持静态的文本),并用新的数字ID(可能包含也可能不包含小数点)替换它们?我想我们应该按照相反的时间顺序来做,这样就不会多次找到较低的数字了?
有没有办法修复我的正则表达式和脚本来实现这个目标?
作为后续问题,我在Electron 表格中有一系列范围,需要转换为新的ID号.
例1:
例2:
有没有办法搜索这些号码并用新号码替换?
例如,从字典中找到5.01并将其替换为5