Hướng dẫn python-docx replace text - python-docx thay thế văn bản

Mô -đun OODOCX được đề cập trong cùng một trang đề cập đến người dùng đến thư mục /ví dụ dường như không có ở đó. Tôi đã đọc tài liệu của Python-docx 0,7.2, cộng với tất cả mọi thứ tôi có thể tìm thấy trong Stackoverflow về chủ đề này, vì vậy xin vui lòng tin rằng tôi đã hoàn thành bài tập về nhà của tôi.
I have read the documentation of python-docx 0.7.2, plus everything I could find in Stackoverflow on the subject, so please believe that I have done my “homework”.

Python là ngôn ngữ duy nhất tôi biết (người mới bắt đầu+, có thể là trung gian), vì vậy xin vui lòng không cho rằng bất kỳ kiến ​​thức nào về C, UNIX, XML, v.v.

Nhiệm vụ: Mở một tài liệu MS-word 2007+ với một dòng văn bản duy nhất trong đó (để giữ cho mọi thứ đơn giản) và thay thế bất kỳ từ khóa nào của từ trong từ điển xảy ra trong dòng văn bản đó với giá trị từ điển của nó. Sau đó đóng tài liệu giữ mọi thứ khác giống nhau.

Dòng văn bản (ví dụ) Chúng tôi sẽ nán lại trong các phòng biển.

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')

Tôi không nhìn thấy bất cứ điều gì trong tài liệu cho phép tôi thực hiện điều này có lẽ nó ở đó nhưng tôi không nhận được nó vì mọi thứ không được đánh vần ở cấp độ của tôi.

Tôi đã theo dõi các đề xuất khác trên trang web này và đã cố gắng sử dụng các phiên bản trước của mô-đun (https://github.com/mikemaccana/python-docx) được cho là có "các phương thức như thay thế, advreplace" như sau: Tôi mở mã nguồn trong trình thông dịch Python và thêm thông tin sau ở cuối (điều này là để tránh các cuộc đụng độ với phiên bản đã được cài đặt 0.7.2):

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 

Chạy này tạo ra thông báo lỗi sau:

NameError: Tên 'CoreProps' không được định nghĩa

Có lẽ tôi đang cố gắng làm điều gì đó không thể thực hiện được nhưng tôi sẽ đánh giá cao sự giúp đỡ của bạn nếu tôi thiếu một cái gì đó đơn giản.

Nếu điều này quan trọng, tôi đang sử dụng phiên bản 64 bit của Canopy của Enters trên OSX 10.9.3

Tôi đang sử dụng Python-docx và cố gắng thay thế văn bản trong các kiểu lưu bảng. Đó là cách bàn của tôi trông

Nhưng nó không hoạt động với các bảng và ô. Tôi cũng đã thử điều này:

Nhưng tôi có một thuộc tínhRorror: 'Bảng' đối tượng không có thuộc tính 'ô'. Làm ơn hãy giúp tôi giải quyết vấn đề này

Câu hỏi :

Cách sử dụng Python-docx để thay thế văn bản trong tài liệu Word và lưu

Mô -đun OODOCX được đề cập trong cùng một trang đề cập đến người dùng đến thư mục /ví dụ dường như không có ở đó. Tôi đã đọc tài liệu của Python-docx 0,7.2, cộng với tất cả mọi thứ tôi có thể tìm thấy trong Stackoverflow về chủ đề này, vì vậy xin vui lòng tin rằng tôi đã hoàn thành bài tập về nhà của tôi.
I have read the documentation of python-docx 0.7.2, plus everything I could find in Stackoverflow on the subject, so please believe that I have done my “homework”.

Python là ngôn ngữ duy nhất tôi biết (người mới bắt đầu+, có thể là trung gian), vì vậy xin vui lòng không cho rằng bất kỳ kiến ​​thức nào về C, UNIX, XML, v.v.

Nhiệm vụ: Mở một tài liệu MS-word 2007+ với một dòng văn bản duy nhất trong đó (để giữ cho mọi thứ đơn giản) và thay thế bất kỳ từ khóa nào của từ trong từ điển xảy ra trong dòng văn bản đó với giá trị từ điển của nó. Sau đó đóng tài liệu giữ mọi thứ khác giống nhau.

Dòng văn bản (ví dụ) Chúng tôi sẽ nán lại trong các phòng biển.

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')

Tôi không nhìn thấy bất cứ điều gì trong tài liệu cho phép tôi thực hiện điều này có lẽ nó ở đó nhưng tôi không nhận được nó vì mọi thứ không được đánh vần ở cấp độ của tôi.

Tôi đã làm theo các đề xuất khác trên trang web này và đã cố gắng sử dụng các phiên bản trước của mô-đun (https://github.com/mikemaccana/python-docx) được cho là có các phương thức như thay thế, advreplace như sau: Tôi mở mã nguồn trong trình thông dịch Python và thêm thông tin sau ở cuối (điều này là để tránh các cuộc đụng độ với phiên bản đã được cài đặt 0.7.2):

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 

Chạy này tạo ra thông báo lỗi sau:

NameError: Tên ‘CoreProps, không được định nghĩa

Có lẽ tôi đang cố gắng làm điều gì đó không thể thực hiện được nhưng tôi sẽ đánh giá cao sự giúp đỡ của bạn nếu tôi thiếu một cái gì đó đơn giản.

Nếu điều này quan trọng, tôi đang sử dụng phiên bản 64 bit của tán cây Enture trên OSX 10.9.3

Trả lời 1:

Phiên bản hiện tại của Python-DOCX không có hàm

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
4 hoặc hàm
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
5. Chúng được yêu cầu khá thường xuyên, nhưng việc triển khai cho trường hợp chung là khá khó khăn và nó đã tăng lên đỉnh của tồn đọng.

Một số người đã có thành công mặc dù, hoàn thành những gì họ cần, sử dụng các cơ sở đã có mặt. Đây là một ví dụ. Nó không liên quan gì đến các phần

for paragraph in document.paragraphs:
    if 'sea' in paragraph.text:
        print paragraph.text
        paragraph.text = 'new text containing ocean'

Để tìm kiếm trong các bảng, bạn sẽ cần sử dụng một cái gì đó như:

for table in document.tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                if 'sea' in paragraph.text:
                    paragraph.text = paragraph.text.replace("sea", "ocean")

Nếu bạn theo đuổi con đường này, bạn có thể khám phá khá nhanh sự phức tạp là gì. Nếu bạn thay thế toàn bộ văn bản của một đoạn văn, sẽ loại bỏ bất kỳ định dạng cấp ký tự nào, như một từ hoặc cụm từ in đậm hoặc in nghiêng.

Nhân tiện, mã từ câu trả lời của @wnnmaw là dành cho phiên bản di sản của Python-docx và won hoạt động ở tất cả các phiên bản sau 0.3.0.

Trả lời #2:

Tôi cần một cái gì đó để thay thế các biểu thức thông thường trong docx. Tôi đã nhận câu trả lời của Scannys. Để xử lý phong cách, tôi đã sử dụng câu trả lời từ: Python docx thay thế chuỗi trong đoạn văn trong khi giữ phong cách
I took scannys answer.
To handle style I’ve used answer from:
Python docx Replace string in paragraph while keeping style

Đã thêm cuộc gọi đệ quy để xử lý các bảng lồng nhau. và nghĩ ra một cái gì đó như thế này:
and came up with something like this:

import re
from docx import Document

def docx_replace_regex(doc_obj, regex , replace):

    for p in doc_obj.paragraphs:
        if regex.search(p.text):
            inline = p.runs
            # Loop added to work with runs (strings with same style)
            for i in range(len(inline)):
                if regex.search(inline[i].text):
                    text = regex.sub(replace, inline[i].text)
                    inline[i].text = text

    for table in doc_obj.tables:
        for row in table.rows:
            for cell in row.cells:
                docx_replace_regex(cell, regex , replace)



regex1 = re.compile(r"your regex")
replace1 = r"your replace string"
filename = "test.docx"
doc = Document(filename)
docx_replace_regex(doc, regex1 , replace1)
doc.save('result1.docx')

Lặp lại từ điển:

for word, replacement in dictionary.items():
    word_re=re.compile(word)
    docx_replace_regex(doc, word_re , replacement)

Lưu ý rằng giải pháp này sẽ chỉ thay thế Regex nếu toàn bộ Regex có cùng kiểu trong tài liệu.

Ngoài ra, nếu văn bản được chỉnh sửa sau khi lưu cùng một văn bản kiểu có thể được chạy riêng biệt. Ví dụ: nếu bạn mở tài liệu có chuỗi testabcd và bạn thay đổi nó thành test test1abcd và lưu, thậm chí dùng cùng kiểu của nó, có 3 lần chạy riêng biệt Thay thế Test1 sẽ không hoạt động.
For example if you open document that has “testabcd” string and you change it to “test1abcd” and save, even dough its the same style there are 3 separate runs “test”, “1”, and “abcd”, in this case replacement of test1 won’t work.

Đây là để theo dõi các thay đổi trong tài liệu. Để đánh dấu nó thành một lần chạy, trong từ, bạn cần phải truy cập vào các tùy chọn của Cameron, Trung tâm tin cậy, và trong các tùy chọn quyền riêng tư của Cameron, không biết đến việc lưu trữ các số ngẫu nhiên để cải thiện độ chính xác của kết hợp và lưu tài liệu.

Được trả lời bởi: szum

Trả lời #3:

Tôi đã nhận được nhiều trợ giúp từ các câu trả lời từ trước đó, nhưng đối với tôi, mã dưới đây có chức năng là chức năng tìm và thay thế đơn giản trong Word sẽ làm. Hi vọng điêu nay co ich.

#!pip install python-docx
#start from here if python-docx is installed
from docx import Document
#open the document
doc=Document('./test.docx')
Dictionary = {"sea": "ocean", "find_this_text":"new_text"}
for i in Dictionary:
    for p in doc.paragraphs:
        if p.text.find(i)>=0:
            p.text=p.text.replace(i,Dictionary[i])
#save changed document
doc.save('./test.docx')

Các giải pháp trên có những hạn chế. 1) Đoạn chứa các bản tin Find Find_this_Text sẽ trở thành văn bản đơn giản mà không có bất kỳ định dạng nào, 2) điều khiển ngữ cảnh trong cùng một đoạn không được thay đổi.

Được trả lời bởi: poin

Trả lời #4:

Trung tâm Dev Office có một mục trong đó một nhà phát triển đã xuất bản (MIT được cấp phép vào thời điểm này) một mô tả về một vài thuật toán xuất hiện để đề xuất một giải pháp cho việc này (mặc dù trong C#, và yêu cầu chuyển đổi):

Trả lời #5:

Vấn đề với nỗ lực thứ hai của bạn là bạn đã xác định các tham số mà

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
6 cần.Bạn cần phải làm điều gì đó như thế này trước khi bạn lưu:

relationships = docx.relationshiplist()
title = "Document Title"
subject = "Document Subject"
creator = "Document Creator"
keywords = []

coreprops = docx.coreproperties(title=title, subject=subject, creator=creator,
                       keywords=keywords)
app = docx.appproperties()
content = docx.contenttypes()
web = docx.websettings()
word = docx.wordrelationships(relationships)
output = r"pathtowhereyouwanttosave"

Trả lời #6:

Anh ấy đã thay đổi API trong Docx Py một lần nữa

cho sự tỉnh táo của mọi người đến đây:

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
0

Trường hợp kiểm tra:

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
1

Có các thư mục

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
7 và
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
8 trong cùng một thư mục mà bạn có
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
9
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
7
and
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
8
in same folder where you have
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
9

e.g.

Hãy chắc chắn để tham số hóa và thay thế các công cụ

Trả lời #7:

Đối với trường hợp bảng, tôi đã phải sửa đổi câu trả lời của @scanny, thành:

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
2

Để làm cho nó hoạt động.Thật vậy, điều này dường như không hoạt động với trạng thái hiện tại của API:

document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
    if word in Dictionary.keys():
        print "found it", Dictionary[word]
        document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
    wordrelationships, output, imagefiledict=None) 
3

Vấn đề tương tự với mã từ đây: https://github.com/python-openxml/python-docx/issues/30#issuecomment-38658149

Được trả lời bởi: basj