2017-05-11 23 views
3

私は単語ファイルからテキストを取り込み、必要なテキストをハイライト表示しようとしています。エージングは​​新しい単語ファイルにテキストを保存します。pythonのテキストを強調表示して単語ファイルに保存します

ANSIエスケープシーケンスを使用してテキストを強調表示できますが、単語ファイルに戻すことができません。

from docx import Document 
doc = Document('t.docx') 
##string present in t.docx '''gnjdkgdf helloworld dnvjk dsfgdzfh jsdfKSf klasdfdf sdfvgzjcv''' 

if 'helloworld' in doc.paragraphs[0].text:  
    high=doc.paragraphs[0].text.replace('helloworld', '\033[43m{}\033[m'.format('helloworld')) 


doc.add_paragraph(high) 
doc.save('t1.docx') 

このエラーが発生します。代わりに、ANSIのエスケープシーケンスを使用しての、あなたは内蔵のFont highlight colorpython-docx年代使うことができ

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters 

答えて

0

screenshot

from docx import Document 
from docx.enum.text import WD_COLOR_INDEX 

doc = Document('t.docx') 
##string present in t.docx '''gnjdkgdf helloworld dnvjk dsfgdzfh jsdfKSf klasdfdf sdfvgzjcv''' 

# Get the first paragraph's text 
p1_text = doc.paragraphs[0].text 

# Create a new paragraph with "helloworld" highlighted 
p2 = doc.add_paragraph() 
substrings = p1_text.split('helloworld') 
for substring in substrings[:-1]: 
    p2.add_run(substring) 
    font = p2.add_run('helloworld').font 
    font.highlight_color = WD_COLOR_INDEX.YELLOW 
p2.add_run(substrings[-1]) 

# Save document under new name 
doc.save('t1.docx') 
+1

を感謝、それは – harsha

+0

グレートを働きました!あなたが問題を解決した場合は、回答を受け入れることができます;)http://stackoverflow.com/help/someone-answers – Josselin

関連する問題