gpt4 book ai didi

python - 使用 Python 自动比较 Word 文档

转载 作者:行者123 更新时间:2023-12-02 07:08:06 24 4
gpt4 key购买 nike

我正在尝试使用 win32com(pywin32) 和 Microsoft Word's Object Model比较两个 Word 文档(在“审阅”->“比较”下自动执行在 Microsoft Word 中比较两个文档的任务)。以下是我为此编写的代码:

import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")

但我收到以下错误:

Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")

File "C:\Python36\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x6\_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings

File "C:\Python36\lib\site-packages\win32com\client\__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)

TypeError: The Python instance can not be converted to a COM object

我无法理解为什么会抛出此错误。我真的很想解决这个问题。请帮忙。

提前致谢

最佳答案

我创建了一个更通用的版本,带有路径和文件检查,如果有人想要的话......

#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

from os import getcwd, path
from sys import argv, exit
from win32com import client

def die(message):
print (message)
exit(1)

def cmp(original_file, modified_file):
dir = getcwd() + '\\'
print('Working...')

# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... aborting\nRemove or rename '+cmp_file)

# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)

print('Saved comparison as: '+cmp_file)
app.Quit()

def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])

if __name__ == '__main__':
main()

关于python - 使用 Python 自动比较 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com