将所有连字符类型替换为ASCII连字符“-”

Dan*_*Man 5 regex hyphen python-3.x

有没有一种方法可以用简单的asi“-”代替所有类型的连字符?我正在寻找适合太空的类似东西:

txt = re.sub(r'[\s]+',' ',txt)
Run Code Online (Sandbox Code Playgroud)

我相信某些非ASCII“-”连字符会避免删除某些特定停用词(由连字符连接的项目名称)的正确过程:

我想用AR-L1003代替此AR–L1003',但是我想对全文进行此操作。

tri*_*cot 4

您只需在类中列出这些连字符即可。这是一个可能的列表——根据您的需要进行扩展:

\n\n
txt = re.sub(r'[\xe2\x80\x90\xe1\xa0\x86\xef\xb9\xa3\xef\xbc\x8d\xe2\x81\x83\xe2\x88\x92]+','-',txt)\n
Run Code Online (Sandbox Code Playgroud)\n\n

标准re库不支持\\p匹配 unicode 类别的语法,但如果可以 import regex,那么就有可能:

\n\n
import regex\n\ntxt = regex.sub(r'\\p{Pd}+', '-', txt)\n
Run Code Online (Sandbox Code Playgroud)\n

  • 请参阅[添加对 Matthew Barnett python 正则表达式模块的支持](https://github.com/firasdib/Regex101/issues/440)。另请阅读 Guido van Rossum 关于该主题的演讲 [早在 2011 年](http://python.6.x6.nabble.com/Should-we-move-to-replace-re-with-regex-td1857882.html) (2认同)