首页 > 解决方案 > 从 MS Word 文件中删除汉字

问题描述

我正在尝试使用python制作一个脚本来从MS word文档中删除汉字,唯一的问题是该文件最初是一个中文word文档,所以格式只是一堆文本框。现在,我的代码能够阅读所有文本框,但由于某种原因,当我尝试替换字符时没有任何反应。我是 python 新手,所以如果有人能帮助我更好地理解我的代码,我将不胜感激。

our_dic = ['≤', '≥', '~', '%', '\n', '\t', '℃']
for x in range(10): 
    our_dic.append(str(x))

temp = set()
trns = None

for x in file_array:
    doc = Document(x)
    rep_dic = {}
    for table in doc.tables:
        print("loading...")
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for letters in paragraph.text:
                        if (ord(letters) < 128) or (letters in our_dic) :
                            temp.add(letters)
                    for k in temp:
                        print(paragraph.text.replace(k, ""))
doc.save(x)
print("I finished your deletion")

现在我正在使用 print 来测试代码,但替换似乎没有打印没有中文字符的代码。

标签: pythonpython-3.xfiledocxfile-writing

解决方案


你为什么要使用 Python,而不是已经内置在 Word 中的 VBA?你应该尝试这样的事情:

Sub DeleteAllObjects()
For i = ActiveDocument.Shapes.Count To 1 Step -1  
    ActiveDocument.Shapes(i).Delete  
Next i
End Sub

或者,搜索代表所有中文字符的特定“格式”,并替换为空格。

有关更多信息,请参阅此内容。

https://www.extendoffice.com/documents/word/748-word-remove-all-text-boxes.html


推荐阅读