【问题标题】:Python - SQLite to CSV Writer Error - ASCII values not parsedPython - SQLite 到 CSV 写入器错误 - 未解析 ASCII 值
【发布时间】:2011-06-23 07:07:55
【问题描述】:

下午,

我在使用 SQLite 到 CSV python 脚本时遇到了一些问题。我搜索过高,也搜索过低,但没有一个对我有用,或者我的语法有问题。

我想替换 SQLite 数据库中不属于 ASCII 表(大于 128)的字符。

这是我一直在使用的脚本:

#!/opt/local/bin/python
import sqlite3
import csv, codecs, cStringIO

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f", 
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([unicode(s).encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

conn = sqlite3.connect('test.db')

c = conn.cursor()

# Select whichever rows you want in whatever order you like
c.execute('select ROWID, Name, Type, PID from PID')

writer = UnicodeWriter(open("ProductListing.csv", "wb"))

# Make sure the list of column headers you pass in are in the same order as your SELECT
writer.writerow(["ROWID", "Product Name", "Product Type", "PID", ])
writer.writerows(c)

我已尝试添加此处所示的“替换”,但出现了相同的错误。 Python: Convert Unicode to ASCII without errors for CSV file

错误是 UnicodeDecodeError。

Traceback (most recent call last):
  File "SQLite2CSV1.py", line 53, in <module>
    writer.writerows(c)
  File "SQLite2CSV1.py", line 32, in writerows
    self.writerow(row)
  File "SQLite2CSV1.py", line 19, in writerow
    self.writer.writerow([unicode(s).encode("utf-8") for s in row])
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 65: ordinal not in range(128)

显然,我希望代码足够健壮,如果遇到超出这些范围的字符,它会用诸如“?”之类的字符替换它。 (\x3f)。

有没有办法在 UnicodeWriter 类中做到这一点?还有一种方法可以使代码变得健壮,不会产生这些错误。

非常感谢您的帮助。

【问题讨论】:

    标签: python unicode csv sqlite


    【解决方案1】:

    如果您只想编写 ASCII CSV,只需使用股票 csv.writer()。要确保传递的所有值确实是 ASCII,请使用 encode('ascii', errors='replace')

    例子:

    import csv
    
    rows = [
      [u'some', u'other', u'more'],
      [u'umlaut:\u00fd', u'euro sign:\u20ac', '']
    ]
    
    with open('/tmp/test.csv', 'wb') as csvFile:
        writer = csv.writer(csvFile)
        for row in rows:
            asciifiedRow = [item.encode('ascii', errors='replace') for item in row]
            print '%r --> %r' % (row, asciifiedRow)
            writer.writerow(asciifiedRow)
    

    这个的控制台输出是:

    [u'some', u'other', u'more'] --> ['some', 'other', 'more']
    [u'umlaut:\xfd', u'euro sign:\u20ac', ''] --> ['umlaut:?', 'euro sign:?', '']
    

    生成的 CSV 文件包含:

    some,other,more
    umlaut:?,euro sign:?,
    

    【讨论】:

    • +1 点。另请注意,UTF-8 不是 ASCII,因此尝试将 UTF-8 字符串提供给需要 ASCII 的函数通常会产生有趣的、意想不到的结果(其中 UnicodeEncodeError 是最明显的 - 一些效果更微妙.)
    【解决方案2】:

    通过访问 unix 环境,这对我有用

    sqlite3.exe a.db .dump > a.sql;
    tr -d "[\\200-\\377]" < a.sql > clean.sql;
    sqlite3.exe clean.db < clean.sql;
    

    (这不是 python 解决方案,但由于其简洁性,它可能会对其他人有所帮助。此解决方案 STRIPS OUT 所有非 ascii 字符,不会尝试替换它们。)

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      相关资源
      最近更新 更多