[python]Replace key words of all documents in a directory
from docx import Document def replace_text_in_word(file_path, new_path, old_texts, new_text): doc = Document(file_path) for old_text in old_texts: for paragraph in doc.paragraphs: if old_text in paragraph.text: paragraph.text = paragraph.text.replace(old_text, new_text) for table in doc.tables: for row in table.rows: for cell in row.cells: if old_text in cell.text: cell.text = cell.text.replace(old_text, new_text) doc.save(new_path) # ''' file_path = 'FCRN.docx' # old_text = 'FCRN' new_text = 'NICHOLASN' replace_text_in_word(file_path, old_text, new_text) ''' ORG_ROOT = './original_doc' import os import sys import shutil def traverse_directory(path,new_root, old_texts, new_text): for root, dirs, files in os.walk(path): for file in files: ext = os.path.splitext(file)[1] doc_path = os.path.join(root, file) new_path = doc_path for old_text in old_texts: new_path = new_path.replace(old_text, new_text) new_path = new_path.replace(ORG_ROOT, new_root) new_dir = os.path.dirname(new_path) print('\ntraverse_directory:\n', doc_path, '\n', new_path, old_text[0], new_text ) if not os.path.exists( new_dir ): os.makedirs( new_dir ) print("mkdir:", new_dir) if ext == '.docx' or ext == '.doc': try: replace_text_in_word(doc_path, new_path, old_texts, new_text) print("replace ok") except: if os.path.exists(doc_path): shutil.copy2(doc_path, new_path) print("erros file:", doc_path) print("rename file errors:", new_path) else: if os.path.exists(doc_path): shutil.copy2(doc_path, new_path) print("rename file others:", new_path) for dir in dirs: doc_path = dir new_path = doc_path for old_text in old_texts: new_path = new_path.replace(old_text, new_text) new_path = new_path.replace(ORG_ROOT, new_root) if os.path.exists(doc_path): shutil.copy2(doc_path, new_path) print("new dir2:", new_path) # main if len(sys.argv) < 2: NEW_STR = 'NICHOLAS_ORIGINAL_NICHOLAS' else: NEW_STR = sys.argv[1] traverse_directory(ORG_ROOT, './new/'+NEW_STR, ['src_str1','src_str2', 'old_str1','old_str2'], NEW_STR)
标签: python
« 不要慌太阳下山有月光
|
加班文化的出路»
日历
最新微语
- 有的时候,会站在分叉路口,不知道向左还是右
2023-12-26 15:34
- 繁花乱开,鸟雀逐风。心自宁静,纷扰不闻。
2023-03-14 09:56
- 对于不可控的事,我们保持乐观,对于可控的事情,我们保持谨慎。
2023-02-09 11:03
- 小时候,
暑假意味着无忧无虑地玩很长一段时间,
节假意味着好吃好喝还有很多长期不见的小朋友来玩...
长大后,
这是女儿第一个暑假,
一个半月...
2022-07-11 08:54
- Watching the autumn leaves falling as you grow older together
2018-10-25 09:45
分类
最新评论
- Goonog
i get it now :) - 萧
@Fluzak:The web host... - Fluzak
Nice blog here! Also... - Albertarive
In my opinion you co... - ChesterHep
What does it plan? - ChesterHep
No, opposite. - mojoheadz
Everything is OK!... - Josephmaigh
I just want to say t... - ChesterHep
What good topic - AnthonyBub
Certainly, never it ...
发表评论: