3

I have a string containing what I guess you'd call a "special" character (o with an umlaut above it) and it's throwing off a DBF library I am using (Ethan Furman's Python DBF library https://pypi.python.org/pypi/dbf retrieve_character() function, error on last line of the function is 'ascii' codec can't decode byte 0xf6 in position 6: ordinal not in range(128) ).

The code:

def retrieve_character(bytes, fielddef, memo, decoder):
    """
    Returns the string in bytes as fielddef[CLASS] or fielddef[EMPTY]
    """
    data = bytes.tostring()
    if not data.strip():
        cls = fielddef[EMPTY]
        if cls is NoneType:
            return None
        return cls(data)
    if fielddef[FLAGS] & BINARY:
        return data
    return fielddef[CLASS](decoder(data)[0]) #error on this line
4

3 回答 3

4

dbf 文件具有代码页属性。听起来您的文件没有正确设置它。您知道使用哪个代码页来创建数据吗?如果是这样,您可以在打开文件时覆盖 dbf 的设置:

table = dbf.Table('dbf_file', codepage='cp437')

cp437只是一个例子——使用任何合适的。

要查看 dbf 文件的当前代码页(假设您在打开时没有覆盖),请使用:

table.codepage

如果您在打开文件时指定了错误的代码页,则非 ascii 数据可能不正确(例如,带有变音符号的 o 可能最终会变成带有波浪号的 n)。

于 2013-09-04T16:05:42.557 回答
0

你试过使用unicodeData.encode('ascii', 'ignore')吗?这会将您的变音符号转换为o同时忽略编码格式之间的任何转换错误。

于 2013-09-04T15:50:09.047 回答
0

有我的方法。dbf 代码:http ://dbf-software.com/dbf-file-encoding.html可以re.findall用来获取所有代码页。##

  1. 标题
 ##
Windows Encodings:
874 Thai Windows
932 Japanese Windows
936 Chinese (PRC, Singapore) Windows
949 Korean Windows
950 Chinese (Hong Kong SAR, Taiwan) Windows
1250 Eastern European Windows
1251 Russian Windows
1252 Windows ANSI
1253 Greek Windows
1254 Turkish Windows
1255 Hebrew Windows
1256 Arabic Windows
MS-DOS Encodings:
437 U.S. MS-DOS
620 Mazovia (Polish) MS-DOS
737 Greek MS-DOS (437G)
850 International MS-DOS
852 Eastern European MS-DOS
857 Turkish MS-DOS
861 Icelandic MS-DOS
865 Nordic MS-DOS
866 Russian MS-DOS
895 Kamenicky (Czech) MS-DOS

伪代码:

import dbf

codepage_list = ['936', '437', ...]

for codepage in codepage_list:

    tabel = dbf.Table('mydbf.dbf', codepage='cp{}'.format(codepage))
    tabel.open(dbf.READ_WRITE)
    try:
        for row in table: 
            print(row)
        table.close()
    except UnicodeDecodeError:
        print('wrong codepage', codepage)
        tabel.close()
        continue
于 2019-07-11T07:31:19.053 回答