【问题标题】:How do I use regex to do this in Python? [closed]如何在 Python 中使用正则表达式来执行此操作? [关闭]
【发布时间】:2010-04-06 23:35:15
【问题描述】:
def symbolsReplaceDashes(text):

我想用连字符替换所有空格和符号。因为我想在 URL 中使用它。

【问题讨论】:

  • 请定义“符号”

标签: python regex url


【解决方案1】:
import re
text = "this isn't alphanumeric"
result = re.sub(r'\W','-',text) # result will be "this-isn-t-alphanumeric"

\W 类与 \w 类相反,后者由字母数字字符和下划线 ([a-zA-Z0-9_]) 组成。因此,将任何与\W 不匹配的字符替换为破折号会留下一个仅包含字母数字、下划线和破折号的字符串,适合 URL。

【讨论】:

  • 他可能还想用破折号代替下划线。
  • 有可能。如果是这种情况,r'[\W-]' 作为模式将轻松完成。
【解决方案2】:

如果您想转义用于 url 的字符串,而不是正则表达式,请使用 urllib.quote()urllib.quote_plus()。对于更复杂的查询,您可能希望使用 urllib.urlencode() 构建 url。您可以使用urllib.unquote()urllib.unquote_plus() 反转引号。

【讨论】:

  • 由于 OP 要求进行有损转换,我的猜测不是他们想要转义字符串,而是他们想要从帖子标题之类的东西生成“漂亮”的 URL,等等。
【解决方案3】:

此响应不使用正则表达式,但也应该有效,可以更好地控制要过滤的符号类型。它使用 unicodedata 模块通过检查字符的类别来删除所有符号。

import unicodedata

# See http://www.dpawson.co.uk/xsl/rev2/UnicodeCategories.html for character categories
replace = ('Sc', 'Sk', 'Sm', 'So', 'Zs')
def symbolsReplaceDashes(text):
    L = []
    for char in text:
        if unicodedata.category(unicode(char)) in replace:
            L.append('-')
        else: L.append(char)
    return ''.join(L)

如果范围超出基本的 ASCII 字母数字字符,您可能需要使用 urllib.quote(output.encode('utf-8')) 之类的东西对字符进行编码。

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多