Skip to main content
 首页 » 编程设计

python之数据库数据的字符串编码/解码问题

2024年11月24日27TianFang

我正在编写一个脚本,用于将 Oracle 数据库中的数据 ETL 到 PostgreSQL。我正在使用 jaydebeapi 连接到 Oracle 和 PSQL 的 psycopy2。我通过将数据流式传输到 copy_from 函数来将数据加载到 PSQL 中——这对于我从 MySQL 数据库中获取的 ETL 非常有效。我对一个字符串有点问题,但我相信他们可能是其他人。我有一个函数可以评估来自 Oracle 的结果集中的每个字段,如果它是一个字符串则将其清除。在源数据库中 Doña Ana 存储在县表中,但它存储为 Do\xf1a Ana,所以当我尝试在 PSQL 中加载它时,它抛出:

invalid byte sequence for encoding "UTF8": 0xf1 0x61 0x20 0x41  
import six 
import unicodedata 
 
def prepdata(value):                                                                                                                                                                                                                                                                                            
    encodedvalue = bytearray(value, 'utf-8') 
    print(encodedvalue) 
    decodedvalue = encodedvalue.decode('utf-8') 
    print(decodedvalue) 
    cleanedvalue = unicodedata.normalize(u'NFD', decodedvalue).encode('ASCII', 'ignore').decode('utf-8') 
    print(cleanedvalue) 
    return cleanedvalue 

输出:

b'Do\\xf1a Ana'                                                                   
Do\xf1a Ana 
Do\xf1a Ana                                                                       

看起来当我尝试对 Do\xf1a Ana 进行编码时,它只是在转义 backslach 而不是转换它。

当我尝试使用解释器规范化字符串时:

>>> x = 'Do\xf1a Ana' 
>>> x 
'Doña Ana' 
>>> p = bytearray(x,'utf-8') 
>>> p 
bytearray(b'Do\xc3\xb1a Ana') 
>>> a = p.decode('utf-8') 
>>> a 
'Doña Ana' 
>>> normal = unicodedata.normalize('NFKD', a).encode('ASCII', 'ignore').decode('utf-8') 
>>> normal 
'Dona Ana' 

谁能解释一下这是怎么回事?显然,来自数据库的值有一些事情正在发生,即使它以 str 的形式出现。

请您参考如下方法:

在对字符串进行初始编码以将其转换为字节后,我能够使用“unicode_escape”解码来完成这项工作。

def prepdata(value):                                                                                                                                                                                                                                                                                            
    encodedvalue = value.encode() 
    decodedvalue = encodedvalue.decode('unicode_escape') 
    cleanedvalue = decodedvalue.replace("\r"," ") 
    # there are also a list of other things happening below  
    # cleaning the string of things that may cause issues like '\n'. 
    return cleanedvalue