使用Python/Django从字符串中移除非ASCII字符
我在数据库里存了一串HTML代码。可惜里面有一些字符,比如®,我想把这些字符换成它们在HTML里的对应写法。这个替换可以在数据库里直接做,也可以在我的Python/Django代码里用查找和替换的方法来实现。
有没有什么建议可以帮我做到这一点呢?
6 个回答
3
我之前发现了这个,所以这并不是我的原创。我找不到来源,但这是我代码中的一段。
def unicode_escape(unistr):
"""
Tidys up unicode entities into HTML friendly entities
Takes a unicode string as an argument
Returns a unicode string
"""
import htmlentitydefs
escaped = ""
for char in unistr:
if ord(char) in htmlentitydefs.codepoint2name:
name = htmlentitydefs.codepoint2name.get(ord(char))
entity = htmlentitydefs.name2codepoint.get(name)
escaped +="&#" + str(entity)
else:
escaped += char
return escaped
你可以这样使用它
>>> from zack.utilities import unicode_escape
>>> unicode_escape(u'such as ® I want')
u'such as ® I want'
7
在这里有一个更简单的答案,大家可以去看看:https://stackoverflow.com/a/18430817/5100481
如果你想从一个字符串中去掉那些不是ASCII字符的内容,比如说字符串叫做 s
,你可以这样做:
s = s.encode('ascii',errors='ignore')
接着,你需要把它从字节格式转换回字符串,可以用这个方法:
s = s.decode()
这些都是在Python 3.6版本中使用的。
23
你可以知道,ASCII字符就是前面128个字符,所以可以用ord
这个函数来获取每个字符的编号,如果编号超出了范围,就把它去掉。
# -*- coding: utf-8 -*-
def strip_non_ascii(string):
''' Returns the string without non ASCII characters'''
stripped = (c for c in string if 0 < ord(c) < 127)
return ''.join(stripped)
test = u'éáé123456tgreáé@€'
print test
print strip_non_ascii(test)
结果
éáé123456tgreáé@€
123456tgre@
请注意,@
这个符号是包含在内的,因为它毕竟也是一个ASCII字符。如果你只想保留某些特定的字符(比如数字和大小写字母),你可以根据ASCII表来限制范围。
补充说明:在重新阅读你的问题后,可能你需要对你的HTML代码进行转义,这样所有字符在显示时才会正确。你可以在模板中使用escape
过滤器。