【问题标题】:openpyxl - convert cell value from 'utf-8 'to ''ascii"openpyxl - 将单元格值从“utf-8”转换为“ascii”
【发布时间】:2017-03-16 03:55:46
【问题描述】:

所以我正在尝试将单元格的值转换为可用的字符串。

我正在尝试做的是在正则表达式中使用单元格值,但它一直抛出错误

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

这只是众多问题之一,因为当我将它从 unicode 转换为 ascii 值时,另一个单元格给了我datetime 错误(就像在日期时间中一样)。

关于如何将其转换为字符串以便在正则表达式中使用的任何建议,因为这些值是可打印的。

【问题讨论】:

    标签: python string type-conversion


    【解决方案1】:

    我不明白这一点,为什么你必须从 utf-8 转换。

    来自unicode 文档
    UTF-8 使用以下规则:

    If the code point is < 128, it’s represented by the corresponding byte value.
    If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes, where each byte of the sequence is between 128 and 255.  
    

    您可以将其转换为ascii,例如:

    u.encode('utf-8') = b"\xea\x80\x80abcd\xde\xb4 u'\\u2019'=\xe2\x80\x99"
    u.encode('ascii', 'ignore') = b"abcd u'\\u2019'="
    u.encode('ascii', 'replace') = b"?abcd? u'\\u2019'=?"
    u.encode('ascii', 'xmlcharrefreplace') = b"&#40960;abcd&#1972; u'\\u2019'=&#8217;"
    u.encode('ascii', 'backslashreplace') = b"\\ua000abcd\\u07b4 u'\\u2019'=\\u2019"  
    

    来自re 文档
    要搜索的模式和字符串都可以是 Unicode 字符串以及 8 位字符串。但是,Unicode 字符串和 8 位字符串不能混合使用:也就是说,您不能将 Unicode 字符串与字节模式匹配,反之亦然;同样,在请求替换时,替换字符串必须与模式和搜索字符串的类型相同。

    re.A
    re.ASCII
    
    Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching.
    This is only meaningful for Unicode patterns, and is ignored for byte patterns.
    
    Note that for backward compatibility, the re.U flag still exists 
    (as well as its synonym re.UNICODE and its embedded counterpart (?u)), 
    but these are redundant in Python 3 since matches are Unicode by default for strings 
    (and Unicode matching isn’t allowed for bytes).
    

    用 Python:3.4.2 测试

    【讨论】:

    • 过几天我得试试。我使用了unicodedata.normalize('NFKD', cell.value).encode('ascii','ignore'),它可以工作
    【解决方案2】:

    在不查看特定字符串的情况下,我会说在将数据加载到 xls(x) 对象之前,需要将其转换为 utf-8 格式。

    cell_value = cell.decode("utf-8")
    

    对于datetime 错误:您需要将包含datetime 的字符串转换为正确的datetime 格式。

    关于 SO 有各种各样的帖子。
    Here 是关于 SO 字符串到日期时间转换的类似问题

    【讨论】:

    • 不幸的是,这不起作用。我通过使用unicodedata.normalize('NFKD', cell.value).encode('ascii','ignore') 解决了这个问题,至于日期时间我只使用了str(cell.value)。它可以print 没有问题但不能将它们转换为普通字符串,这似乎很奇怪。
    猜你喜欢
    • 2019-10-31
    • 2011-06-19
    • 2012-08-04
    • 2011-06-26
    • 2015-08-06
    • 2015-04-07
    • 2011-01-16
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多