Cảm ơn đã trả lời, nó hoạt động!
Và kể từ khi các file nguồn là trong các định dạng khác nhau, tôi đã thêm một danh sách các định dạng nguồn sẽ bị xét xử theo thứ tự (sourceFormats
), và trên UnicodeDecodeError
tôi cố gắng định dạng tiếp theo:
from __future__ import with_statement
import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector
targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()
def get_encoding_type(current_file):
detector.reset()
for line in file(current_file):
detector.feed(line)
if detector.done: break
detector.close()
return detector.result['encoding']
def convertFileBestGuess(filename):
sourceFormats = ['ascii', 'iso-8859-1']
for format in sourceFormats:
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
def convertFileWithDetection(fileName):
print("Converting '" + fileName + "'...")
format=get_encoding_type(fileName)
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
print("Error: failed to convert '" + fileName + "'.")
def writeConversion(file):
with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
for line in file:
targetFile.write(line)
# Off topic: get the file list and call convertFile on each file
# ...
(EDIT bởi Rudro Badhon: điều này kết hợp thử nhiều định dạng ban đầu cho đến khi bạn không nhận được ngoại lệ cũng như phương pháp thay thế sử dụng chardet.universaldetector)
Nguồn
2008-10-10 16:14:45
Đọc() sẽ luôn đọc toàn bộ tệp - bạn có thể muốn .read (BLOCKSIZE), trong đó BLOCKSIZE là một số lượng phù hợp để đọc/ghi cùng một lúc. – Brian
Đó là sự thật, cảm ơn bạn. Tôi sẽ sửa đổi ví dụ của tôi. – DzinX