簡體   English   中英

如何用特殊字符 python 替換字符串列表中的完全匹配?

[英]How to replace exact matches from a list of strings with special characters python?

我正在從 pandas dataframe 列中刪除我 list_of_strings 中的所有完全匹配項。 但是,我並不真正了解正在使用的 re.escape 。 無論我的 list_of_strings 變量和 dataframe 列中存在什么類型的字符,我都想確保此代碼將刪除所有匹配項。 re.escape 到底有什么作用? 我已經閱讀了文檔,但對正則表達式比較陌生,並且希望得到更外行的術語解釋。

import pandas as pd
import re

df = pd.DataFrame(
    {
        "ID": [1, 2],
        "name": [
            "I have a %$$#form with @#$%$#%@/}\p special characters!!!!",
            "can we: remove the EXACT matches !#$#%$^%$&^(*&*)(*&)_&#",
        ],

    }
)


list_of_strings = ['can we: remove', 'with @#$%$#%@/}\p special characters!!!!','EXACT']


p = re.compile('|'.join(map(re.escape, list_of_strings)))
df['cleaned_text'] = [p.sub(' ', text) for text in df['name']] 


在正則表達式中,某些符號具有含義並觸發某些功能,當您想顯式匹配符號而不觸發其 function 時,您可以轉義它。

現在 re.escape 只是一種手動避免 escaping 字符列表的方法。

而不是 escaping (添加\ )手動像這樣:

"\$\[\]\^"

你可以像你寫的 function 一樣簡單地做。

模式 = "|".join(map(re.escape, "[$[]^")) "\$|\[|\]|\^"

要查看您的代碼做什么,只需打印 p。

list_of_strings = ['can we: remove', 'with @#$%$#%@/}\p special characters!!!!','EXACT']


p = '|'.join(map(re.escape, list_of_strings))
print(p)

如您所見,所有字符都已轉義\

使用 for 循環:

for i in list_of_strings:
    df['name'] = df['name'].str.replace(i, '', regex=False)

print(df)

   ID                                   name
0   1                     I have a %$$#form 
1   2   the  matches !#$#%$^%$&^(*&*)(*&)_&#

也許有更簡單的方法:

df.name.str.replace(list_of_strings[0],'', regex=False)\
       .str.replace(list_of_strings[1],'', regex=False)\
       .str.replace(list_of_strings[2],'', regex=False)

Output:

0                       I have a %$$#form 
1     the  matches !#$#%$^%$&^(*&*)(*&)_&#
Name: name, dtype: object

暫無
暫無

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

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