python中的php preg_替换

2024-10-02 00:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个php函数,可以清除任何特殊字符,现在我想在Python中创建一个类似php的函数

我的php函数:

function cleanString($text)
{
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), trim($text));
}

我在Python中进行了如下尝试:

def clean(text):
    utf8 = {
        '/[áàâãªä]/u'   :   'a',
        '/[ÁÀÂÃÄ]/u'    :   'A',
        '/[ÍÌÎÏ]/u'     :   'I',
        '/[íìîï]/u'     :   'i',
        '/[éèêë]/u'     :   'e',
        '/[ÉÈÊË]/u'     :   'E',
        '/[óòôõºö]/u'   :   'o',
        '/[ÓÒÔÕÖ]/u'    :   'O',
        '/[úùûü]/u'     :   'u',
        '/[ÚÙÛÜ]/u'     :   'U',
        '/ç/'           :   'c',
        '/Ç/'           :   'C',
        '/ñ/'           :   'n',
        '/Ñ/'           :   'N',
        '/–/'           :   '-', # UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    :   ' ', # Literally a single quote
        '/[“”«»„]/u'    :   ' ', # Double quote
        '/ /'           :   ' ', # nonbreaking space (equiv. to 0x160)
    }
    return re.sub(utf8.keys(), utf8.values(), text.strip())

但显示错误并显示以下消息:

unhashable type: 'dict_keys'

Tags: to函数textutf8keysarrayutfquote
1条回答
网友
1楼 · 发布于 2024-10-02 00:27:29

Python的^{}不像PHP的^{}那样支持数组样式的输入。您需要迭代替换,例如

def clean(text):
    utf8 = {
        '[áàâãªä]'   :   'a',
        '[ÁÀÂÃÄ]'    :   'A',
        '[ÍÌÎÏ]'     :   'I',
        '[íìîï]'     :   'i',
        '[éèêë]'     :   'e',
        '[ÉÈÊË]'     :   'E',
        '[óòôõºö]'   :   'o',
        '[ÓÒÔÕÖ]'    :   'O',
        '[úùûü]'     :   'u',
        '[ÚÙÛÜ]'     :   'U',
        'ç'          :   'c',
        'Ç'          :   'C',
        'ñ'          :   'n',
        'Ñ'          :   'N',
        '–'          :   '-', # UTF-8 hyphen to "normal" hyphen
        '[’‘‹›‚]'    :   ' ', # Literally a single quote
        '[“”«»„]'    :   ' ', # Double quote
        ' '          :   ' ', # nonbreaking space (equiv. to 0x160)
    }
    text = text.strip()
    for pat, repl in utf8.items():
        text = re.sub(pat, repl, text, 0, re.U)
    return text

还要注意,python在正则表达式周围不使用分隔符,您可以直接将u标志传递给re.sub。我已经调整了你的代码来处理这些问题

示例用法:

print(clean('ÂôÑ‹Î'))

输出:

AoN I

相关问题 更多 >

    热门问题