我希望这可以帮助
import re
s = '''Product
Etli Barbekü Brioche® Menü(Mktr:1,Id:20046,Top:26,70)\r\n
Whopper® Menü(Mktr:1,Id:10001,25)\r\n,Whopper® Menü(Mktr:1,Top:22,5)\r\n
Köfteburger® Menü(Mktr:1,Id:10030,Top:16,95)\r\n,Köfteburger® Menü(Mktr:1,İndirimli Vodafone Menüsü (WhopperJr.Menü&Tavukburger)(Mktr:1,Id:98196,Top:19,9)\r\n,Big Royale Kampanyası(Mktr:1,Id:98449,Top:32,Top:18,Double Köfteburger® Menü(Mktr:1,Id:20042,Top:21,Kral İkili(Mktr:1,Id:98176,Top:28,9
(Mktr:1,Id:98584,Top:17,75)\r\n,(Mktr:1,Id:99595,Top:4,5)\r\n
(Mktr:1,Id:99009,Id:99065,Top:10,75)\r\n
YENI BIG KING MENU(Mktr:1,Id:20026,Top:20,70)\r\n
(Mktr:1,Id:99928,45)\r\n
(Mktr:1,Top:14,75)\r\n
(Mktr:1,Id:115000,Top:0,01)\r\n,Whopper Cheese Menü(Mktr:1,Id:20001,5)\r\n,Id:98535,Ranch Sos(Mktr:1,Id:90008,75)\r\n'''
regex = re.compile(r'Top:(\d+)(,)(\d+)')
out = []
for st in s.splitlines():
if regex.search(st):
out.append(regex.sub(r'Top:\1.\3',st))
else:
out.append(st)
print('\r\n'.join(out))
其中的输出应如下所示
Product
Etli Barbekü Brioche® Menü(Mktr:1,Top:26.70)
Whopper® Menü(Mktr:1,Top:26.25),Top:22.5)
Köfteburger® Menü(Mktr:1,Top:16.95),Top:19.9),Top:32.9),Top:18.95),Top:21.95),Top:28.9
(Mktr:1,Top:17.75),Top:4.5)
(Mktr:1,Top:28.95),Top:10.75)
YENI BIG KING MENU(Mktr:1,Top:20.70)
(Mktr:1,Top:32.45)
(Mktr:1,Top:14.75),Top:14.75)
(Mktr:1,Top:0.01),Top:22.5),Top:18.25),Top:4.5),Top:0.75)
,
您可以使用此:
import re
print(re.sub(r"(Top:\d{1,}),(\d{1,})",r"\1.\2",string))
仅将,
替换为.
结果
(Mktr:1,Top:0.75)
,
找到了可能的解决方案here:
import re
# Function to run on matches
def reg_replace(match_obj):
s = match_obj.group(0)
s = s.replace(",",".")
return s
pat = r"Top:\d+,\d+"
re_pat = re.compile(pat)
test = '(Mktr:1,75)\r\n'
res = re.sub(re_pat,reg_replace,test)
res
# '(Mktr:1,Top:0.01)\r\n,Top:22.5)\r\n,Top:18.25)\r\n,Top:4.5)\r\n,Top:0.75)\r\n'
它定义了一个函数,该函数处理用正则表达式指定的匹配。
,
这是一种解决方案:
matches = re.findall(r"Top:\d{1,2},\d{1,2}",your_str)
for i in matches:
new_i = i.replace(",".")
your_str = your_str.replace(i,new_i)
,
str1 = """Product
Etli Barbekü Brioche® Menü(Mktr:1,Whopper®
Menü(Mktr:1,Köfteburger®
Menü(Mktr:1,İndirimli Vodafone Menüsü
(WhopperJr.Menü&Tavukburger)(Mktr:1,İndirimli Vodafone
Menüsü (WhopperJr.Menü&Tavukburger)(Mktr:1,Big Royale
Kampanyası(Mktr:1,Double Köfteburger®
Menü(Mktr:1,Whopper Cheese
Menü(Mktr:1,75)\r\n"""
first_occurence = str1.index("Top")
list_top_price = []
for i in range(0,str1.count("Top")): # count the number of occurrence of "Top"
first_occurence = str1.index("Top",first_occurence + i)
last_occurence = str1.index(")",first_occurence + 5)
# append all occurrence of substring start with "Top"
list_top_price.append(str1[first_occurence: last_occurence])
str_formated = ''
tempstr = str1 # copy of str1
for t in list_top_price:
comma_replaced = str(t).replace(",".") # comma replaced string
str_formated = tempstr.replace(str(t),comma_replaced)
tempstr = str_formated
print(str2)
OutPut ::
Product
Etli Barbekü Brioche® Menü(Mktr:1,Top:16.95)