从字符串中删除特殊字符 (¡)

Removing special characters (¡) from a string

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

{..., Name: ¡Hi!, ...}

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

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

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

所以这个例子是这样的:

我有一个 collection,其中包含以下详细信息

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

   ],
   "screenshot_urls":[

   ]
}

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

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

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

f.close();

作为一个用户 post 在 this page, you should take a look at the Unicode tutorial in the docs: https://docs.python.org/2/howto/unicode.html

上编辑

这是因为您尝试使用 ASCII 范围之外的字符,它只有 128 个符号。我不久前发现了一篇关于此的非常棒的文章,我将尝试在此处 post 找到它。

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

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

>>> 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'

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

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

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

或者,您可以write the file as UTF-8,它几乎可以代表地球上所有的字符。

您正在尝试在 "strict" 模式下将 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