一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python截取两个单词之间的内容方法

时间:2018-12-25 编辑:猪哥 来源:一聚教程网

1. __init__ 初始化文件路径,关键字1,关键字2;

2. key_match 使用with open 方法,以二进制方式(也可以改成utf-8,GB2312)读取文件内容(支持txt/log格式);

3. buffer = f.read() 一致性读取到buffer中,读取超大文件会发生MemoryError(可以设置每次读取的size或切割文件)。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
import re
 
#文本所在路径,引号前加r指按路径处理
#关键字word1,word2,换关键字,需修改引号间的内容
 
class match2Words(object):
 lines=0
 def __init__(self,path,word1,word2):
  self.path = path
  self.word1 = word1
  self.word2 = word2
 def key_match(self):
  with open(self.path,'rb') as f:
   buffer = f.read()
   pattern = re.compile(self.word1+b'(.*?)'+self.word2,re.S)
   result = pattern.findall(buffer)
   if result != []:
    print(result)
    #self.lines +=1
    #print("匹配到的行数:",self.lines)
   else:
    print("没有找到你输入的关键字")
 
path = input("请输入要分析的log地址:")
word1 = b"begin"
word2 = b"end"
matchWords = match2Words(path, word1, word2)
matchWords.key_match()

热门栏目