write python codes to search for keyword "宿舍" in several word files in a folder
- User
write python codes to search for keyword "宿舍" in several word files in a folder
- Assistant
You can use the
osanddocxlibraries in Python to achieve this.Here's an example code that searches for the keyword "宿舍" in all Word files within a folder:
pythonimport os from docx import Document def search_keyword_in_word_files(folder_path, keyword): # List all files in the specified folder files = os.listdir(folder_path) # Iterate over each file and search for the keyword for file_name in files: if file_name.endswith(".docx"): file_path = os.path.join(folder_path, file_name) document = Document(file_path) paragraphs = document.paragraphs # Iterate over each paragraph and search for the keyword for paragraph in paragraphs: if keyword in paragraph.text: print(f"Keyword found in file '{file_name}':") print(paragraph.text) print() - User
write python codes to convert the file extensions of all word files in one folder from "doc" to "docx"
- Assistant
To convert the file extensions of all Word files in a folder from ".doc" to ".docx", you can use the
oslibrary in Python. Here's an example code that accomplishes this:pythonimport os def convert_doc_to_docx(folder_path): # List all files in the specified folder files = os.listdir(folder_path) # Iterate over each file and check if it is a Word document with .doc extension for file_name in files: if file_name.endswith(".doc"): # Create the old and new file paths old_file_path = os.path.join(folder_path, file_name) new_file_name = file_name.replace(".doc", ".docx") new_file_path = os.path.join(folder_path, new_file_name) # Rename the file os.rename(old_file_path, new_file_path) print(f"Converted file: {file_name} -> {new_file_name}") # Specify the folder path where your Word files are located folder_path = "path/to/your/folder" # Call the convert_doc_to_docx function convert_doc_to_docx(folder_path)