簡體   English   中英

沒有找到一個好的正則表達式模式來以正確的順序替換字符串(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)這種字符串時,它會給出一個 output 像這樣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"'\1'", l))
    for f in x:    
        y.append(re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]',f))

print(x)
print(y)

給出:

x:["'plug'", "'[plug'+'wallet]'", "'(wallet'-'phone)'"]
y:["df['plug']", "df['[plug']+df['wallet]']", "df['(wallet']-df['phone)']"]

圖案錯了嗎? 預期 output:

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['\1']",w) for w in lst]

print(z)
["df['plug']", "[df['plug']+df['wallet']]", "(df['wallet']-df['phone'])"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM