[英]How to replace text in curly brackets with another text based on comparisons using Python Regex
我對正則表達式不熟悉。 我有一個看起來像這樣的字符串:
str = "abc/def/([default], [testing])"
和一本字典
dict = {'abc/def/[default]' : '2.7', 'abc/def/[testing]' : '2.1'}
在將dict中的每個元素與str進行比較之后,我想使用Python RE,以這種形式的str:
str = "abc/def/(2.7, 2.1)"
使用Python RE如何做有幫助嗎?
PS不是任何任務的一部分,而是我工作中項目的一部分,我花了很多時間來找出解決方案,但徒勞無功。
這里可能不需要正則表達式。 希望這可以幫助
lhs,rhs = str.split("/(")
rhs1,rhs2 = rhs.strip(")").split(", ")
lhs+="/"
print "{0}({1},{2})".format(lhs,dict[lhs+rhs1],dict[lhs+rhs2])
產量
abc/def/(2.7,2.1)
import re
st = "abc/def/([default], [testing], [something])"
dic = {'abc/def/[default]' : '2.7',
'abc/def/[testing]' : '2.1',
'bcd/xed/[something]' : '3.1'}
prefix_regex = "^[\w*/]*"
tag_regex = "\[\w*\]"
prefix = re.findall(prefix_regex, st)[0]
tags = re.findall(tag_regex, st)
for key in dic:
key_prefix = re.findall(prefix_regex, key)[0]
key_tag = re.findall(tag_regex, key)[0]
if prefix == key_prefix:
for tag in tags:
if tag == key_tag:
st = st.replace(tag, dic[key])
print st
OUTPUT:
abc/def/(2.7, 2.1, [something])
這是使用re
模塊的解決方案。
假設:
[]
)中 (
,可變部分列表和a )
[]
Python代碼:
import re
class splitter:
pref = re.compile("[^(]+")
iden = re.compile("\[[^]]*\]")
def __init__(self, d):
self.d = d
def split(self, s):
m = self.pref.match(s)
if m is not None:
p = m.group(0)
elts = self.iden.findall(s, m.span()[1])
return p, elts
return None
def convert(self, s):
p, elts = self.split(s)
return p + "(" + ", ".join((self.d[p + elt] for elt in elts)) + ")"
用法:
s = "abc/def/([default], [testing])"
d = {'abc/def/[default]' : '2.7', 'abc/def/[testing]' : '2.1'}
sp = splitter(d)
print(sp.convert(s))
輸出:
abc/def/(2.7, 2.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.