Python 2.7,docx,用特殊字符替换文本

时间:2016-09-09 13:09:22

标签: python-2.7 special-characters python-docx

我试图找出如何用特殊字符替换文本。 这就是我现在所拥有的。它可以替换普通文本,但它不能处理像Č,Ř,Ž,Ý等特殊字符...

def printInfo( q, qy ):
        for p in document.paragraphs:
                if qy in p.text:
                    inline = p.runs
                    for i in range(len(inline)):
                        if qy in inline[i].text:
                            text = inline[i].text.replace(qy, q)
                            inline[i].text = text
                    print p.text   
        return;
printInfo('text with special character', 'old text')

错误讯息:

Traceback (most recent call last):
  File "C:\Dopisy\example3.py", line 83, in <module>
    printInfo( x, 'prijmeni')
  File "C:\Dopisy\example3.py", line 68, in printInfo
    inline[i].text = text
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\text\run.py", line 163, in text
    self._r.text = text
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\text\run.py", line 104, in text
    _RunContentAppender.append_to_run_from_text(self, text)
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\text\run.py", line 134, in append_to_run_from_text
    appender.add_text(text)
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\text\run.py", line 143, in add_text
    self.flush()
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\text\run.py", line 165, in flush
    self._r.add_t(text)
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\text\run.py", line 41, in add_t
    t = self._add_t(text=text)
  File "C:\Python27\lib\site-packages\python_docx-0.8.6-py2.7.egg\docx\oxml\xmlchemy.py", line 275, in _add_child
    setattr(child, key, value)
  File "lxml.etree.pyx", line 953, in lxml.etree._Element.text.__set__ (src\lxml\lxml.etree.c:44956)
  File "apihelpers.pxi", line 677, in lxml.etree._setNodeText (src\lxml\lxml.etree.c:20273)
  File "apihelpers.pxi", line 1395, in lxml.etree._utf8 (src\lxml\lxml.etree.c:26485)
ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

从我到目前为止发现的内容可能与此处描述的问题相同:0 How to resolve "ValueError: All strings must be XML compatible... 但是所描述的解决方案对我不起作用,或者我只是不知道如何在我的情况下使用它。 如果你能以任何方式帮助我,我们将不胜感激。

0 个答案:

没有答案