脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python截取两个单词之间的内容方法

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

2021-05-07 00:17qq_34500270 Python

今天小编就为大家分享一篇python截取两个单词之间的内容方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/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()

以上这篇python截取两个单词之间的内容方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_34500270/article/details/82899554

延伸 · 阅读

精彩推荐