簡體   English   中英

Python正則表達式,刪除除Unicode字符串的連字符以外的所有標點符號

[英]Python regex, remove all punctuation except hyphen for unicode string

我有以下代碼可用於刪除正則表達式字符串中的所有標點符號:

import regex as re    
re.sub(ur"\p{P}+", "", txt)

我如何更改它以允許連字符? 如果您能解釋您是如何做到的,那將很棒。 我了解在這里,如果我錯了,請糾正我,在標點符號之后加上P。

[^\P{P}-]+

\\P\\p的補充-不是標點符號。 所以這個匹配任何 (不帶標點破折號) -導致除破折號所有標點符號。

范例: http//www.rubular.com/r/JsdNM3nFJ3

如果您希望采用非卷積方式,則可以選擇\\p{P}(?<!-) :匹配所有標點符號,然后檢查它是否不是破折號(使用負向后看)。
工作示例: http : //www.rubular.com/r/5G62iSYTdk

如果您必須堅持使用標准庫,則可以使用re模塊執行以下操作:

# works in python 2 and 3
import re
import string

remove = string.punctuation
remove = remove.replace("-", "") # don't remove hyphens
pattern = r"[{}]".format(remove) # create the pattern

txt = ")*^%{}[]thi's - is - @@#!a !%%!!%- test."
re.sub(pattern, "", txt) 
# >>> 'this - is - a - test'

如果性能很重要,則可能要使用str.translate ,因為它比使用regex更快 在Python 3中,代碼為txt.translate({ord(char): None for char in remove})

您可以指定要手動刪除的標點符號,例如[._,]也可以提供一個函數而不是替換字符串:

re.sub(r"\p{P}", lambda m: "-" if m.group(0) == "-" else "", text)

暫無
暫無

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

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