admin管理员组文章数量:1291179
I'm currently working on a program to be able to copy the contents from a word doc and create a new document with the contents, but I want to be able select which parts of the doc to copy. There are headings throughout and those are what I've been using as a focal point because they have a unique style tag (Heading2) so the code goes through and if you say copy section 3 it will go until it finds 'section 3' with that style and pastes it into the new doc.
My issue is the tables, i have a function to copy the contents and that works perfectly but when i try to associate it to certain sections it gets a bit wonky. It works up until about half way through where one of the sections has 2 tables in it versus the previous ones which only have 1 table per section. This causes problems because my current code just associates 1-to-1 so table 1 goes in section 1, table 2 in section 2 and so on, but when theres 2 tables a section the first one goes in the right section but the second table goes in the next section making everything out of sync so I want to make it so copies based off of the style tag, that way i could have as many tables as i want in a section and they'd all be copied into the correct section. Everything I've tried so far doesnt work so I'm hoping someone might be able to help me alter it.
def associate_tables_with_sections(doc): # Written up
sections = []
current_section = None
table_index = 0
# Loop through the paragraphs to extract content for sections
for para in doc.paragraphs:
if para.style.name == 'Heading 2' and para.text.strip():
# Starting a new section based on Heading 2
if current_section:
sections.append(current_section) # Save the previous section
current_section = {'heading': para.text.strip(), 'content': [], 'tables': []}
elif current_section:
# Add content paragraphs to the current section
current_section['content'].append(para)
# After loop ends, append the last section
if current_section:
sections.append(current_section)
# Now associate tables with the appropriate section (by proximity)
for table in doc.tables:
if sections:
sections[table_index % len(sections)]['tables'].append(table)
table_index += 1
return sections
This is the code that currently works, but doesnt copy more than 1 table per section where I want it to be able to copy however many different tables are in that section whether it be 1 or 20. I've tried a couple of other solutions and tried feeding it into chatgpt, but those solutions either don't do anything different and make it more complicated or just break it entirely. Any help would be much appreciated.
本文标签: pythonCopying contents from one word doc to anotherStack Overflow
版权声明:本文标题:python - Copying contents from one word doc to another - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741526274a2383485.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论