当我导入时docx我有这个错误:
>File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/docx-0.2.4-py3.3.egg/docx.py", line 30, in <module>
from exceptions import PendingDeprecationWarning
ImportError: No module named 'exceptions'
Run Code Online (Sandbox Code Playgroud)
如何解决此错误(python3.3,docx 0.2.4)?
我正在尝试使用python-docxmodule(pip install python-docx),但它似乎非常混乱,因为在github repo测试样本中他们使用的是opendocx函数,但在readthedocs中他们正在使用Document类.即使他们只是展示如何将文本添加到docx文件而不是读取现有文件?
第一个(opendocx)不起作用,可能会被弃用.对于第二种情况,我试图使用:
from docx import Document
document = Document('test_doc.docx')
print document.paragraphs
Run Code Online (Sandbox Code Playgroud)
它返回了一份清单 <docx.text.Paragraph object at 0x... >
然后我做了:
for p in document.paragraphs:
print p.text
Run Code Online (Sandbox Code Playgroud)
它返回了所有文本,但缺少一些东西.控制台上的文本中不存在所有URL(CTRL + CLICK转到URL).
有什么问题?为什么缺少网址?
如何在不迭代循环的情况下获得完整的文本(类似open().read())
同一页面中提到的oodocx模块将用户引用到似乎不存在的/ examples文件夹.
我已经阅读了python-docx 0.7.2的文档,以及我在Stackoverflow中可以找到的关于这个主题的所有内容,所以请相信我已经完成了我的"功课".
Python是我所知道的唯一语言(初学者+,也许是中级),所以请不要假设任何C,Unix,xml等知识.
任务:打开一个带有单行文本的ms-word 2007+文档(为了简单起见),并用字典值替换在该行文本中出现的Dictionary中的任何"关键"字.然后关闭文档,保持其他所有内容相同.
文本行(例如)"我们将在海中徘徊."
from docx import Document
document = Document('/Users/umityalcin/Desktop/Test.docx')
Dictionary = {‘sea’: “ocean”}
sections = document.sections
for section in sections:
print(section.start_type)
#Now, I would like to navigate, focus on, get to, whatever to the section that has my
#single line of text and execute a find/replace using the dictionary above.
#then save the document in the usual way.
document.save('/Users/umityalcin/Desktop/Test.docx')
Run Code Online (Sandbox Code Playgroud)
我没有在文档中看到任何允许我这样做的东西 - 也许它就在那里但是我没有得到它,因为我的关卡并没有拼写出来.
我已经关注了这个网站上的其他建议,并尝试使用该模块的早期版本(https://github.com/mikemaccana/python-docx)应该有"像replace,advReplace这样的方法",如下所示:我打开python解释器中的源代码,并在最后添加以下内容(这是为了避免与已安装的0.7.2版本冲突):
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word …Run Code Online (Sandbox Code Playgroud) 我正在处理一个试图开发网络应用程序的问题,其中一部分将上传的docx文件转换为pdf文件(经过一些处理后).使用python-docx和其他方法,我不需要安装word的Windows机器,甚至linux上的libreoffice,用于大多数处理(我的web服务器是pythonanywhere - linux但没有libreoffice,没有sudo或apt install权限).但转换为pdf似乎需要其中之一.通过在这里和其他地方探索问题,这是我到目前为止:
import subprocess
try:
from comtypes import client
except ImportError:
client = None
def doc2pdf(doc):
"""
convert a doc/docx document to pdf format
:param doc: path to document
"""
doc = os.path.abspath(doc) # bugfix - searching files in windows/system32
if client is None:
return doc2pdf_linux(doc)
name, ext = os.path.splitext(doc)
try:
word = client.CreateObject('Word.Application')
worddoc = word.Documents.Open(doc)
worddoc.SaveAs(name + '.pdf', FileFormat=17)
except Exception:
raise
finally:
worddoc.Close()
word.Quit()
def doc2pdf_linux(doc):
"""
convert a …Run Code Online (Sandbox Code Playgroud) 问题陈述:从.docx文件中提取包含自动编号的部分.
我尝试使用python-docx从.docx文件中提取文本,但它排除了自动编号.
from docx import Document
document = Document("wadali.docx")
def iter_items(paragraphs):
for paragraph in document.paragraphs:
if paragraph.style.name.startswith('Agt'):
yield paragraph
if paragraph.style.name.startswith('TOC'):
yield paragraph
if paragraph.style.name.startswith('Heading'):
yield paragraph
if paragraph.style.name.startswith('Title'):
yield paragraph
if paragraph.style.name.startswith('Heading'):
yield paragraph
if paragraph.style.name.startswith('Table Normal'):
yield paragraph
if paragraph.style.name.startswith('List'):
yield paragraph
for item in iter_items(document.paragraphs):
print item.text
Run Code Online (Sandbox Code Playgroud) 如何在表格中设置单元格宽度?到目前为止,我得到了:
from docx import Document
from docx.shared import Cm, Inches
document = Document()
table = document.add_table(rows=2, cols=2)
table.style = 'TableGrid' #single lines in all cells
table.autofit = False
col = table.columns[0]
col.width=Inches(0.5)
#col.width=Cm(1.0)
#col.width=360000 #=1cm
document.save('test.docx')
Run Code Online (Sandbox Code Playgroud)
没有我在col.width中设置的数量或单位,其宽度不会改变.
我使用Python-docx来生成Microsoft Word文档.用户在写作时想要这样:例如:"早上好每个人,这是我的%(profile_img)你喜欢吗?" 在HTML字段中,我创建一个word文档,我从数据库中恢复用户的图片,然后用用户图片替换关键字%(profile_img)s,而不是在文档的末尾.使用Python-docx,我们使用此指令添加图片:
document.add_picture('profile_img.png', width=Inches(1.25))
Run Code Online (Sandbox Code Playgroud)
图片已添加到文档中,但问题是它在文档末尾添加.使用python在microsoft word文档中的特定位置添加图片是不可能的?我没有在网上找到任何答案,但已经看到人们在其他地方要求相同的解决方案.
谢谢(注意:我不是一个非常体验的程序员,除了这个尴尬的部分,我的其余代码将非常基本)
我正在尝试使用python-docx模块替换文件中的单词并保存新文件,但需要注意新文件必须具有与旧文件完全相同的格式,但替换单词.我该怎么做?
docx模块有一个saveocx,它有7个输入:
除了替换的单词外,如何将原始文件中的所有内容保持不变?
作为一个例子,我有一个通用脚本,使用python-docx输出默认表格样式(此代码运行正常):
import docx
d=docx.Document()
type_of_table=docx.enum.style.WD_STYLE_TYPE.TABLE
list_table=[['header1','header2'],['cell1','cell2'],['cell3','cell4']]
numcols=max(map(len,list_table))
numrows=len(list_table)
styles=(s for s in d.styles if s.type==type_of_table)
for stylenum,style in enumerate(styles,start=1):
label=d.add_paragraph('{}) {}'.format(stylenum,style.name))
label.paragraph_format.keep_with_next=True
label.paragraph_format.space_before=docx.shared.Pt(18)
label.paragraph_format.space_after=docx.shared.Pt(0)
table=d.add_table(numrows,numcols)
table.style=style
for r,row in enumerate(list_table):
for c,cell in enumerate(row):
table.row_cells(r)[c].text=cell
d.save('tablestyles.docx')
Run Code Online (Sandbox Code Playgroud)
接下来,我打开文档,突出显示拆分表并在段落格式下选择"Keep with next",这成功阻止了表格在页面中拆分:
这是非破坏表的XML代码:
您可以看到突出显示的行显示应该将表保持在一起的段落属性.所以我写了这个函数并将其粘贴d.save('tablestyles.docx')在行上方的代码中:
def no_table_break(document):
tags=document.element.xpath('//w:p')
for tag in tags:
ppr=tag.get_or_add_pPr()
ppr.keepNext_val=True
no_table_break(d)
Run Code Online (Sandbox Code Playgroud)
当我检查XML代码时,段属性标记设置正确,当我打开Word文档时,将检查所有表的"保持下一个"框,但表仍然在页面之间拆分.我错过了一个XML标签或者阻止它正常工作的东西吗?
我需要使用python-docx在表格中设置单元格边框,但找不到如何操作.请帮忙.
python-docx ×10
python ×9
docx ×4
ms-word ×3
python-2.7 ×2
python-3.x ×2
column-width ×1
image ×1
pagination ×1
pdf ×1
replace ×1
text ×1
xml ×1