如何使用Python扫描多个文档格式(CSV、文本、MS Word)中的字符串?
问题…
假设您有一个目录,其中包含各种格式的文件,需要搜索特定关键字。
准备工作…
安装以下包。
1. beautifulsoup4
2. python-docx
操作方法…
1. 编写一个函数来搜索CSV格式的字符串。我将使用csv.reader模块遍历文件并搜索字符串,找到则返回True,否则返回False。
示例
def csv_stringsearch(input_file, input_string): """ Function: search a string in csv files. args: input file , input string """ with open(input_file) as file: for row in csv.reader(file): for column in row: if input_string in column.lower(): return True return False
2. 搜索文本文件的函数。这有点棘手,因为我们需要处理编码。存在数千种编码,确定编码格式可能是最困难的部分。当然,我们可以联系创建文本文件的用户,但我们正在进行自动化处理。
因此,我们将使用UnicodeDammit来确定编码。
示例
def text_stringsearch(input_file, input_string): """ Function: search a string in text files. args: input file , input string """ with open(filename, 'rb') as file: content = file.read(1024) guessencoding = UnicodeDammit(content) encoding = guessencoding.original_encoding # Open and read with open(input_file, encoding=encoding) as file: for line in file: if input_string in line.lower(): return True return False
3. 编写一个函数来搜索MS Word文档中的字符串。
示例
def MSDocx_stringsearch(input_file, input_string): """ Function: search a string in MS Word documents. args: input file , input string """ doc = docx.Document(input_file) for paragraph in doc.paragraphs: if input_string in paragraph.text.lower(): return True return False
4. 现在,我们需要一个主函数来遍历文件并调用相应的函数以及要搜索的字符串。这里我假设代码和要搜索的输入文件位于同一目录中。如果您的目录位于不同的位置,您可以添加路径参数。
示例
def main(input_string): """ Function: Open the current directory and search for a string in all the files args: input string """ for root, dirs, files in os.walk('.'): for file in files: # Get the file extension extension = file.split('.')[-1] if extension in function_maps: search_file = function_maps.get(extension) full_file_path = os.path.join(root, file) if search_file(full_file_path, input_string): print(f' *** Yeah String found in {full_file_path}')
5. 通过创建一个字典来将我们的函数映射到文件扩展名。
示例
EXTENSIONS ={ 'csv': csv_stringsearch, 'txt': text_stringsearch, 'docx': MSDocx_stringsearch, }
示例
6. 将所有内容整合在一起。
import os import argparse import csv import docx from bs4 import UnicodeDammit def csv_stringsearch(input_file, input_string): """ Function: search a string in csv files. args: input file , input string """ with open(input_file) as file: for row in csv.reader(file): for column in row: if input_string in column.lower(): return True return False def MSDocx_stringsearch(input_file, input_string): """ Function: search a string in MS Word documents. args: input file , input string """ doc = docx.Document(input_file) for paragraph in doc.paragraphs: if input_string in paragraph.text.lower(): return True return False def text_stringsearch(input_file, input_string): """ Function: search a string in text files. args: input file , input string """ with open(input_file, 'rb') as file: content = file.read(1024) guessencoding = UnicodeDammit(content) encoding = guessencoding.original_encoding # Open and read with open(input_file, encoding=encoding) as file: for line in file: if input_string in line.lower(): return True return False def main(input_string): """ Function: Open the current directory and search for a string in all the files args: input string """ for root, dirs, files in os.walk('.'): for file in files: # Get the file extension extension = file.split('.')[-1] if extension in function_mapping: search_file = function_mapping.get(extension) full_file_path = os.path.join(root, file) if search_file(full_file_path, input_string): print(f' *** Yeah String found in {full_file_path}') function_mapping = { 'csv': csv_stringsearch, 'txt': text_stringsearch, 'docx': MSDocx_stringsearch, } if __name__ == '__main__': string_to_search = 'Hello' print(f'Output \n') main(string_to_search.lower())
输出
*** Yeah String found in .\Hello_World.docx *** Yeah String found in .\My_Amazing_WordDoc.docx
7. 如果您想将程序更改为命令行执行,则可以使用argparse。
示例
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-s', type=str, help='Input string to search', default='Hello') args = parser.parse_args() main(args.s.lower())
广告