I have recently written a script to extract all bookmarks from a pdf and save them in a docx file. It works for 90% of the files but unfortunaltely there are some that seem to have problems with unicode.
I get the bookmarks in a list like this:
[[u'3. Mechatronik f\xfcr Doppelkupplungsgetriebe, Sicherungshalter B, Sicherung 14 auf Sicherungshalter C', 2],
[u'4. Geber f\xfcr Getriebeeingangsdrehzahl, Hydraulikdruckgeber 1 f\xfcr automatisches Getriebe, Magnetventil 2, Magnetventil \x04, Magnetventil 5', 2],
[u'5. W\xe4hlhebel, Schalter f\xfcr W\xe4hlhebel in P gesperrt, Magnet f\xfcr W\xe4hlhebelsperre', 2],
[u'6. W\xe4hlhebel, Geber 2 f\xfcr Antriebswellendrehzahl, W\xe4hlhebel-Positionsanzeige', 2]]
When i try to run the function i get the error:
ValueError('All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters',)
Code:
from docx import Document
list1 = [[u'3. Mechatronik f\xfcr Doppelkupplungsgetriebe, Sicherungshalter B, Sicherung 14 auf Sicherungshalter C', 2],
[u'4. Geber f\xfcr Getriebeeingangsdrehzahl, Hydraulikdruckgeber 1 f\xfcr automatisches Getriebe, Magnetventil 2, Magnetventil \x04, Magnetventil 5', 2],
[u'5. W\xe4hlhebel, Schalter f\xfcr W\xe4hlhebel in P gesperrt, Magnet f\xfcr W\xe4hlhebelsperre', 2],
[u'6. W\xe4hlhebel, Geber 2 f\xfcr Antriebswellendrehzahl, W\xe4hlhebel-Positionsanzeige', 2]]
def save_docx(list1):
document = Document('default.docx')
file = open("Error_Log.txt", 'w')
for i in list1:
try:
p = document.add_paragraph()
p.add_run(i[0]).bold = True
except Exception as e:
file.write(repr(e) + '\n')
file.close()
document.save('Bookmarks.docx')
save_docx(list1)
Im guessing the problem ist the \x0
but I can not figure out how to remove parts like this without ruining the whole document.
I have tried diffenrent encodings and anything else I could find online but nothing worked so far.
Any help would be much appreciated!