python对不同类型文件的字符查找

TXT文件:

    def txt_handler(self, f_name, find_str):
"""
处理txt文件
:param file_name:
:return:
"""
line_count = 1;
file_str_dict = {}
if os.path.exists(f_name):
f = open(f_name, 'r', encoding='utf-8')
for line in f :
if find_str in line:
file_str_dict['file_name'] = f_name
file_str_dict['line_count'] = line_count
break
else:
line_count += 1
return file_str_dict

docx文件

需要用到docx包

pip install python-docx
参考https://python-docx.readthedocs.io/en/latest/
from docx import Document

def docx_handler(self, f_name, find_str):
"""
处理word docx文件
:param file_name:
:return:
"""
# line_count = 1;
file_str_dict = {}
if os.path.exists(f_name):
document = Document(f_name) # 打开文件x.docx
for paragraph in document.paragraphs: # 每个获取段落
# print(paragraph.text)
if find_str in paragraph.text:
file_str_dict['file_name'] = f_name
# file_str_dict['line_count'] = line_count
break return file_str_dict

doc文件:

python没有专门处理doc文件的包,需要把doc转换成docx,再用docx文件类型方式进行处理

from win32com import client as wc

def doc_to_docx(self, fileName):
# 将doc转换成docx
word = wc.Dispatch("Word.Application")
doc = word.Documents.Open(fileName)
# 使用参数16表示将doc转换成docx,保存成docx后才能 读文件
FileNameDocx = fileName[:-4] + '.docx'
doc.SaveAs(FileNameDocx, 16)
doc.Close()
word.Quit()
return FileNameDocx

pdf文件:

这里使用PDFMiner包

python3安装

python -m pip install pdfminer.six 

参考文章

https://dzone.com/articles/exporting-data-from-pdfs-with-python

import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage def pdf_handler(self, f_name, find_str):
"""
处理pdf文件
:param file_name:
:return:
"""
# line_count = 1;
file_str_dict = {}
if os.path.exists(f_name):
# pdf = pdfplumber.open(f_name) # 打开文件x.pdf
for page in self.extract_text_by_page(f_name):
# 获取当前页面的全部文本信息,包括表格中的文字
if find_str in page:
file_str_dict['file_name'] = f_name
# file_str_dict['line_count'] = line_count
break
return file_str_dict @staticmethod
def extract_text_by_page(pdf_path):
"""
按页读取PDF
生成器函数按页生成(yield)了文本
:param pdf_path:
:return:
"""
with open(pdf_path, 'rb') as fh:
for page in PDFPage.get_pages(fh,
caching=True,
check_extractable=True):
resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(resource_manager, fake_file_handle)
page_interpreter = PDFPageInterpreter(resource_manager, converter)
page_interpreter.process_page(page)
text = fake_file_handle.getvalue()
yield text # 使用生成器
# close open handles
converter.close()
fake_file_handle.close()

python对不同类型文件(doc,txt,pdf)的字符查找的更多相关文章

  1. doc或docx(word)或image类型文件批量转PDF脚本

    doc或docx(word)或image类型文件批量转PDF脚本 1.实际生产环境中遇到文件展示只能适配PDF版本的文件,奈何一万个文件有七千个都是word或者image类型的,由此搞个脚本批量转换下 ...

  2. python反编译chm文件并生成pdf文件

    # -*- coding: utf-8 -*- import os import os.path import logging import pdfkit original_chm = r'C:\Us ...

  3. python基础——python解析yaml类型文件

    一.yaml介绍 yaml全称Yet Another Markup Language(另一种标记语言).采用yaml作为配置文件,文件看起来直观.简洁.方便理解.yaml文件可以解析字典.列表和一些基 ...

  4. 【python】实例-创建文件并通过键盘输入字符

    import os lnend=os.linesep ##windows行结束符号是“\r\n” FileName=raw_input("please input filename:&quo ...

  5. python数据处理(三)之处理pdf文件

    代码以及资料 https://github.com/jackiekazil/data-wrangling 1.前言 尽可能地寻找可以替代pdf格式的数据 2.解析pdf的编程方法 安装slate pi ...

  6. python基础——元组、文件及其它

    Python核心数据类型--元组 元组对象(tuple)是序列,它具有不可改变性,和字符串类似.从语法上讲,它们便在圆括号中,它们支持任意类型.任意嵌套及常见的序列操作. 任意对象的有序集合:与字符串 ...

  7. solr6.6 导入 pdf/doc/txt/json/csv/xml文件

    文本主要介绍通过solr界面dataimport工具导入文件,包括pdf.doc.txt .json.csv.xml等文件,看索引结果有什么不同.其实关键是managed-schema.solrcon ...

  8. python第六篇文件处理类型

    阅读目录 一 文件操作 二 打开文件的模式 三 操作文件的方法 四 文件内光标移动 五 文件的修改   文件处理                                             ...

  9. [大数据]-Fscrawler导入文件(txt,html,pdf,worf...)到Elasticsearch5.3.1并配置同义词过滤

    fscrawler是ES的一个文件导入插件,只需要简单的配置就可以实现将本地文件系统的文件导入到ES中进行检索,同时支持丰富的文件格式(txt.pdf,html,word...)等等.下面详细介绍下f ...

随机推荐

  1. PAT 乙级 1003.我要通过! C++/Java

    1003 我要通过! (20 分) 题目来源 “答案正确”是自动判题系统给出的最令人欢喜的回复.本题属于 PAT 的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则 ...

  2. ES6 手册

    不用就忘, 把阮大大的地址列在这儿: http://es6.ruanyifeng.com/#README

  3. MATLAB问题小集合

    1.未定义与 'struct' 类型的输入参数相对应的函数 'tb_optparse' 在运行matlab程序时,出现上述错误. 原因是tb_optparse在common文件夹里面,没在robot文 ...

  4. HDU - 6643: Ridiculous Netizens(点分治+依赖背包+空间优化)

    题意:给定带点权的树,问多少个连通块,其乘积<=M; N<=2000,M<1e6; 思路:连通块-->分治: 由于普通的树DP在合并的时候复杂度会高一个M,所以用依赖背包来做. ...

  5. 13、Python文件处理、os模块、json/pickle序列化模块

    一.字符编码 Python3中字符串默认为Unicode编码. str类型的数据可以编码成其他字符编码的格式,编码的结果为bytes类型. # coding:gbk x = '上' # 当程序执行时, ...

  6. python预课03 三元表达式示例,函数定义示例,七段彩码管绘制示例

    三元表达式 s = '不下雨' if s == '下雨': print('带伞') if s == '不下雨': print('不带伞') #等效与以下语句 print('带伞' if s == '下 ...

  7. set_multiset_functor

    #include<iostream> #include<string> #include<set> using namespace std; class Stude ...

  8. spark延迟调度与动态资源管理

    Spark中的延迟调度 Spark的Task的调度过程有五个本地性级别:PROCESS_NODE.NODE_LOCAL.NO_PREF.RACK_LOCAL.ANY.在理想的状态下,我们肯定是想所有的 ...

  9. iOS系统的两个循环

    1.事件循环: 2.显示循环:displaylink:系统定时从gpu缓存获取图片信息显示在屏幕.

  10. Python 弹出框代码

      from ctypes import * user32 = windll.LoadLibrary('user32.dll')#调用dll文件 #a是得到弹出框的选择按钮的值 user32.Mess ...