我想將兩行代碼合二為一。第一個是刪除所有 string.punctuations。我使用的代碼如下:df[col].apply(lambda x: re.sub(r'[!\"#$%&\'()*+,-.\/:;<=>?@[\\]^_`{|}~]+', '', x))第二個是去掉一些特殊字符(我不知道怎么表達這種雙引號,比如; 這些與普通引號“’‘”不同):'""'df[col].apply(lambda x: re.sub(r'[“’‘”]', '', x))我想用一行代碼將它們全部刪除。我試圖簡單地將第二個完全匹配添加到第一個,但事實證明文本中沒有刪除第二個匹配。我想知道為什么以及如何有效地刪除這些punctuations.需要清理的示例文本可能是:text = '“Client” refers to Client or “”any User uploads or otherwise supplies to, or stores in, the Services under Client’s account.'
1 回答

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
根據您的回答,我相信這就是您正在尋找的答案:
import re text = '“Client” refers to Client or “”any User uploads or otherwise supplies to, or stores in, the Services under Client’s account.' re.sub(r'[^\w|^\d|^\s]+', '', text)
輸出:
'Client refers to Client or any User uploads or otherwise supplies to or stores in the Services under Clients account'
替換所有字符,除了:
^\w
單詞字符,如 AZ 和 az^\d
數字^\s
空格
考慮到特殊字符列表的廣度,這種排他性過濾比包容性過濾更有效。
添加回答
舉報
0/150
提交
取消