Отредактируйте свой вопрос, указав, что происходит (точное сообщение об ошибке и трассировку (копировать / вставить, не печатать из памяти)), чтобы заставить вас думать, что проблема заключается в "плохом Юникоде".
Получите chardet и загрузите в него свой дамп MySQL. Скажите нам, что там написано.
Покажите нам первые 200–300 байтов вашего дампа, например, используя. print repr(dump[:300])
Обновление Вы написали "" "Как видите, chardet думает, что это файл ascii, но в середине этого примера есть" \ x1e ", что заставляет lxml вызывать исключение "" "
Я не вижу здесь "плохого юникода".
chardet правильно. С чего вы взяли, что "\ x1e" не ASCII? Это символ ASCII, управляющий символ C0 с именем «РАЗДЕЛИТЕЛЬ ЗАПИСИ».
В сообщении об ошибке говорится, что у вас недопустимый символ. Это тоже правильно. Единственными управляющими символами, действительными в XML, являются "\t"
, "\r"
и "\n"
. MySQL должен ворчать об этом и / или предлагать вам способ избежать этого, например. _x001e_
(юк!)
Учитывая контекст, похоже, что этот символ может быть удален без потерь. Вы можете исправить вашу базу данных, или вы можете удалить подобные символы из вашего дампа (после проверки, что они все исчезают) или вы можете выбрать менее требовательный и менее громоздкий формат вывода, чем XML.
Обновление 2 Вы, вероятно, хотите, чтобы пользователь iterparse()
не потому, что это ваша конечная цель, а потому, что вы хотите сэкономить память. Если вы используете такой формат, как CSV, у вас не будет проблем с памятью.
Обновление 3 В ответ на комментарий @Purrell:
попробуй сам, чувак. pastie.org/3280965
Вот содержимое этой пасточки; заслуживает сохранения:
from lxml.etree import etree
data = '\t<articletext><p>The cafeteria rang with excited voices. Our barbershop quartet, The Bell \r Tones was asked to perform at the local Home for the Blind in the next town. We, of course, were glad to entertain such a worthy group and immediately agreed . One wag joked, "Which uniform should we wear?" followed with, "Oh, that\'s right, they\'ll never notice." The others didn\'t respond to this, in fact, one said that we should wear the nicest outfit we had.</p><p>A small stage was set up for us and a pretty decent P.A. system was donated for the occasion. The audience was made up of blind persons of every age, from the thirties to the nineties. Some sported sighted companions or nurses who stood or sat by their side, sharing the moment equally. I observed several German shepherds lying at their feet, adoration showing in their eyes as they wondered what was going on. After a short introduction in which we identified ourselves, stating our voice part and a little about our livelihood, we began our program. Some songs were completely familiar and others, called "Oh, yeah" songs, only the chorus came to mind. We didn\'t mind at all that some sang along \x1e they enjoyed it so much.</p><p>In fact, a popular part of our program is when the audience gets to sing some of the old favorites. The harmony parts were quite evident as they tried their voices to the different parts. I think there was more group singing in the old days than there is now, but to blind people, sound and music is more important. We received a big hand at the finale and were made to promise to return the following year. Everyone was treated to coffee and cake, our quartet going around to the different circles of friends to sing a favorite song up close and personal. As we approached a new group, one blind lady amazed me by turning to me saying, "You\'re the baritone, aren\'t you?" Previously no one had ever been able to tell which singer sang which part but this lady was listening with her whole heart.</p><p>Retired portrait photographer. Main hobby - quartet singing.</p></articletext>\n'
magical_parser = etree.XMLParser(encoding='utf-8', recover=True)
tree = etree.parse(StringIO(data), magical_parser)
Чтобы запустить его, нужно исправить один импорт, а другой поставить. Данные чудовищные. Нет выходных данных, чтобы показать результат. Вот замена с данными, сокращенными до самого необходимого. 5 частей текста ASCII (исключая <
и >
), которые являются действительными символами XML, заменяются на t1
, ..., t5
. Нарушитель \x1e
между t2
и t3
.
[output wraps at column 80]
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> from cStringIO import StringIO
>>> data = '<article><p>t1</p><p>t2\x1et3</p><p>t4
</p><p>t5</p></article>'
>>> magical_parser = etree.XMLParser(encoding='utf-8', recover=True)
>>> tree = etree.parse(StringIO(data), magical_parser)
>>> print(repr(tree.getroot().text))
'<p>t1</p><p>t2t3/ppt4/ppt5/p'
Не то, что я бы назвал "восстановление"; после плохого символа символы <
и >
исчезают.
Пасти ответил на мой вопрос "Что дает вам идею, что кодировка = 'utf-8' решит его проблему?" Это было вызвано утверждением «Однако существует опция« кодирования », которая исправила бы вашу проблему». Но кодировка = ascii выдает тот же результат. Так же опуская кодировку arg. Это НЕ проблема кодирования. Дело закрыто.