有没有办法将unicode字符写入docx文件?我试过了python-docx但是,它给了我TypeError
。
回溯
追踪(最近一次呼叫最后一次):
档案"< ipython-input-1-ba89c735995d>",第1行,in runfile(' H:/Python/Practice/new/download.py' ;, wdir =' H:/ Python / Practice / new')
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py",第866行,在runfile中 execfile(filename,namespace)
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py",第102行,在execfile中 exec(compile(f.read(),filename,' exec'),命名空间)
文件" H:/Python/Practice/new/download.py",第37行,在 document.add_paragraph(story.encode(" UTF-8&#34))
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ document.py",第63行,在add_paragraph中 return self._body.add_paragraph(text,style)
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ blkcntnr.py",第36行,在add_paragraph中 paragraph.add_run(文本)
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ text \ paragraph.py",第37行,在add_run中 run.text = text
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ text \ run.py",第163行,文字 self._r.text = text
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ oxml \ text \ run.py",第104行,文字 _RunContentAppender.append_to_run_from_text(self,text)
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ oxml \ text \ run.py",第134行,在append_to_run_from_text appender.add_text(文本)
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ oxml \ text \ run.py",第142行,在add_text中 self.add_char(char)的
文件" C:\ Program Files \ Anaconda3 \ lib \ site-packages \ docx \ oxml \ text \ run.py",第156行,在add_char中 elif char in' \ r \ n':
TypeError:' in<字符串>'需要字符串作为左操作数,而不是int
我试图抓一个网站并将文本写入MS Word文件。文字采用当地语言(孟加拉语)。当我在控制台上打印story
时,它可以完美地打印整个文本。
码
import requests
from docx import Document
from bs4 import BeautifulSoup
url = "some url"
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
story = soup.find("div", {"dir": "ltr"}).get_text().replace("<br />", "\n", len(response.text))
title = "title"
document = Document()
document.add_heading(title, 0)
document.add_paragraph(story.encode("utf-8"))
document.save(title + ".docx")
答案 0 :(得分:2)
在Python 3中,str
ings(应该)自动支持Unicode,因此您不需要像编码到UTF-8那样做任何特殊的事情。
document.add_paragraph(story)
# ^ just do this directly, no need to call `.encode('utf-8')`
虽然您可以将Unicode字符写入文档,但字处理程序使用的默认文本呈现引擎可能不支持它。您可能需要specify a font以确保字符不会变为□□□□。
run = document.add_paragraph(story).add_run()
font = run.font
font.name = 'Vrinda'