没有找到一个好的正则表达式模式来以正确的顺序替换字符串(python)
Not finding a good regex pattern to substitute the strings in a correct order(python)
我有一个字符串格式的列名列表,如下所示:
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
现在我想使用正则表达式将 df[]
和 " ' "
添加到每个列名,我这样做了,当列表具有 (wallet-phone)
这种字符串时,它给出了一个像这样输出 df[('wallet']-df['phone')]
。我怎么会这样 (df['wallet']-df['phone']),
是不是我的模式错了。请参考以下:
import re
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
x=[]
y=[]
for l in lst:
x.append(re.sub(r"([^+\-*\/'\d]+)", r"''", l))
for f in x:
y.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[]',f))
print(x)
print(y)
给出:
x:["'plug'", "'[plug'+'wallet]'", "'(wallet'-'phone)'"]
y:["df['plug']", "df['[plug']+df['wallet]']", "df['(wallet']-df['phone)']"]
模式有误吗?
预期输出:
x:["'plug'", "['plug'+'wallet']", "('wallet'-'phone')"]
y:["df['plug']", "[df['plug']+df['wallet']]", "(df['wallet']-df['phone'])"]
我也试过 ([^+\-*\/()[]'\d]+)
这种模式,但它并没有避免 () or []
查找单词并将其包含在字典参考中可能更容易:
import re
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
z = [re.sub(r"(\w+)",r"df['']",w) for w in lst]
print(z)
["df['plug']", "[df['plug']+df['wallet']]", "(df['wallet']-df['phone'])"]
我有一个字符串格式的列名列表,如下所示:
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
现在我想使用正则表达式将 df[]
和 " ' "
添加到每个列名,我这样做了,当列表具有 (wallet-phone)
这种字符串时,它给出了一个像这样输出 df[('wallet']-df['phone')]
。我怎么会这样 (df['wallet']-df['phone']),
是不是我的模式错了。请参考以下:
import re
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
x=[]
y=[]
for l in lst:
x.append(re.sub(r"([^+\-*\/'\d]+)", r"''", l))
for f in x:
y.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[]',f))
print(x)
print(y)
给出:
x:["'plug'", "'[plug'+'wallet]'", "'(wallet'-'phone)'"]
y:["df['plug']", "df['[plug']+df['wallet]']", "df['(wallet']-df['phone)']"]
模式有误吗? 预期输出:
x:["'plug'", "['plug'+'wallet']", "('wallet'-'phone')"]
y:["df['plug']", "[df['plug']+df['wallet']]", "(df['wallet']-df['phone'])"]
我也试过 ([^+\-*\/()[]'\d]+)
这种模式,但它并没有避免 () or []
查找单词并将其包含在字典参考中可能更容易:
import re
lst = ["plug", "[plug+wallet]", "(wallet-phone)"]
z = [re.sub(r"(\w+)",r"df['']",w) for w in lst]
print(z)
["df['plug']", "[df['plug']+df['wallet']]", "(df['wallet']-df['phone'])"]