【问题标题】:Remove non-ASCII characters from a string using python / django使用 python / django 从字符串中删除非 ASCII 字符
【发布时间】:2011-02-14 03:27:45
【问题描述】:

我有一个存储在数据库中的 HTML 字符串。不幸的是,它包含诸如®之类的字符 我想用它们的 HTML 等价物替换这些字符,无论是在 DB 本身中,还是在我的 Python / Django 代码中使用 Find Replace。

关于如何做到这一点的任何建议?

【问题讨论】:

  • 为什么要替换它们?如果您的 unicode 正确,它们应该可以正常显示在页面中。无论您做什么,不要将 HTML 编码的数据放入数据库中。
  • +1 表示 bobince:您确定要替换它们吗?您只需要通过添加元标记(例如 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />)来告诉浏览器您正在使用 unicode

标签: python regex django unicode replace


【解决方案1】:

您可以使用前 128 个 ASCII 字符,因此使用 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 table的范围

已编辑:再次阅读您的问题后,也许您需要转义您的 HTML 代码,以便所有这些字符在渲染后正确显示。您可以在模板上使用escape 过滤器。

【讨论】:

  • AFAIK Django 的转义过滤器不会转义 Unicode 字符,它只会转义这些字符:&lt; &gt; " ' &amp;
【解决方案2】:

我不久前发现了这个,所以这绝不是我的工作。我找不到源代码,但这是我的代码中的 sn-p。

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 &#174 I want'

【讨论】:

    【解决方案3】:

    你不应该做任何事情,因为 Django 会自动转义字符:

    见:http://docs.djangoproject.com/en/dev/topics/templates/#id2

    【讨论】:

    • Django 不会自动转义 Unicode 字符,它只会转义这些字符:&lt; &gt; " ' &amp;
    【解决方案4】:

    要去掉特殊的 xml, html 字符 '', '&' 你可以使用 cgi.escape:

    import cgi
    test = "1 < 4 & 4 > 1"
    cgi.escape(test)
    

    将返回:

    '1 &lt; 4 &amp; 4 &gt; 1'
    

    这可能是您避免问题所需的最低限度。 要了解更多信息,您必须了解字符串的编码。 如果它适合您的 html 文档的编码,则您不必做更多的事情。 如果不是,则必须转换为正确的编码。

    test = test.decode("cp1252").encode("utf8")
    

    假设你的字符串是 cp1252 并且你的 html 文档是 utf8

    【讨论】:

      【解决方案5】:

      此代码 sn-p 可能会对您有所帮助。

      #!/usr/bin/env python
      # -*- coding: UTF-8 -*-
      
      def removeNonAscii(string):
          nonascii = bytearray(range(0x80, 0x100))
          return string.translate(None, nonascii)
      
      nonascii_removed_string = removeNonAscii(string_to_remove_nonascii)
      

      编码定义在这里非常重要,在第二行完成。

      【讨论】:

        【解决方案6】:

        https://stackoverflow.com/a/18430817/5100481 有一个更简单的答案

        要从字符串中删除非 ASCII 字符 s,请使用:

        s = s.encode('ascii',errors='ignore')

        然后使用以下命令将其从字节转换回字符串:

        s = s.decode()

        这一切都使用 Python 3.6

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-21
          • 2010-12-04
          • 2016-07-28
          • 2023-03-18
          • 2017-06-18
          相关资源
          最近更新 更多