【问题标题】:Removing special characters (¡) from a string从字符串中删除特殊字符 (¡)
【发布时间】:2016-01-23 09:29:44
【问题描述】:

我正在尝试从集合中写入文件。该集合具有像¡这样的特殊字符,这会产生问题。例如,集合中的内容具有以下详细信息:

{...,名称:¡嗨!,...}

现在我正在尝试将相同的内容写入文件,但出现错误

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa1' in position 0: ordinal not in range(128)

我尝试过使用here 提供的解决方案,但没有成功。如果有人可以帮助我,那就太好了:)

所以例子是这样的:

我有一个包含以下详细信息的集合

{ "_id":ObjectId("5428ead854fed46f5ec4a0c9"), 
   "author":null,
   "class":"culture",
   "created":1411967707.356593,
   "description":null,
   "id":"eba9b4e2-900f-4707-b57d-aa659cbd0ac9",
   "name":"¡Hola!",
   "reviews":[

   ],
   "screenshot_urls":[

   ]
}

现在我尝试从集合中访问此处的 name 条目,我通过在集合上迭代它来做到这一点,即

f = open("sample.txt","w");

for val in exampleCollection:
   f.write("%s"%str(exampleCollection[val]).encode("utf-8"))

f.close();

【问题讨论】:

标签: python unicode special-characters


【解决方案1】:

正如一位用户在this 页面上发布的那样,您应该查看文档中的 Unicode 教程:https://docs.python.org/2/howto/unicode.html

您正在尝试使用 ASCII 范围之外的字符,即只有 128 个符号。不久前我发现了一篇非常棒的文章,我会尝试在此处找到并发布。

编辑:啊,这里是:http://www.joelonsoftware.com/articles/Unicode.html

【讨论】:

    【解决方案2】:

    删除不需要的字符的最简单方法是指定要删除的字符。

    >>> import string
    >>> validchars = string.ascii_letters + string.digits + ' '
    >>> s = '¡Hi there!'
    >>> clean = ''.join(c for c in s if c in validchars)
    >>> clean
    'Hi there'
    

    如果某些形式的标点符号没问题,请将它们添加到有效字符中。

    【讨论】:

      【解决方案3】:

      这将删除字符串中所有不是有效 ASCII 的字符。

      >>> '¡Hola!'.encode('ascii', 'ignore').decode('ascii')
      'Hola!'
      

      您也可以write the file as UTF-8,它可以代表地球上几乎所有的角色。

      【讨论】:

        【解决方案4】:

        您正在尝试在“严格”模式下将 unicode 转换为 ascii:

        >>> help(str.encode)
        Help on method_descriptor:
        
        encode(...)
            S.encode([encoding[,errors]]) -> object
        
            Encodes S using the codec registered for encoding. encoding defaults
            to the default encoding. errors may be given to set a different error
            handling scheme. Default is 'strict' meaning that encoding errors raise
            a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
            'xmlcharrefreplace' as well as any other name registered with
            codecs.register_error that is able to handle UnicodeEncodeErrors.
        

        您可能想要以下内容之一:

        s = u'¡Hi there!'
        
        print s.encode('ascii', 'ignore')    # removes the ¡
        print s.encode('ascii', 'replace')   # replaces with ?
        print s.encode('ascii','xmlcharrefreplace') # turn into xml entities
        print s.encode('ascii', 'strict')    # throw UnicodeEncodeErrors
        

        【讨论】:

          猜你喜欢
          • 2011-04-11
          • 2019-11-09
          • 2011-08-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多