我有一个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'
Python的^{} 不像PHP的^{} 那样支持数组样式的输入。您需要迭代替换,例如
还要注意,python在正则表达式周围不使用分隔符,您可以直接将
u
标志传递给re.sub
。我已经调整了你的代码来处理这些问题示例用法:
输出:
相关问题 更多 >
编程相关推荐