下午,
我在使用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类中执行此操作?我可以通过一种方式使代码健壮,不会产生这些错误。
非常感谢您的帮助。
答案 0 :(得分: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 :(得分:0)
通过访问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字符,不会尝试替换它们。)