example extracts a specific substring in a file
123142134sadfsadlzsfdsafszdfdsq431535e4qt/version= ' 1.0 '/DFASFDSFSDGSASDGDSAFE3QREGHQA
12314sfdsafszdfdsq431535e4qt/version= ' 1.21 '/dfasfdsfsdgsfe3qreghqa
123142134sadfsadlzdfdsq431535e4qt/ version= ' 1.334 '/dfasfsdgdsafe3qreghqa
123142134sadfdsafszdfdsq431535e4qt/version= ' 1.423 '/ DFASFDSFASDGDSAFE3QREGHQA
123142134sadfsafdsq431535e4qt/version= ' 1.5 '/DFASFDSFSDGSSAFE3QREGHQA
123142134sadfsdsafszdfdsq431535e4qt/version= ' 1.6 '/DFASFDSFSAFE3QREGHQA
Extracts version field data. Scheme one: Read each row, split separate, find target string, intercept substring.
def getversion (filename):
versionlist = []
with open (filename, ' r ') as lines: for line in
lines:
tmplist = Line.split ('/')
idx=tmplist[1].find (' = ')
versionlist.append (tmplist[1][idx+1:])
return Versionlist
Scenario Two: Extracting the target substring using the forward backward configuration of the regular.
def getVersion2 (filename):
versionlist=[] with
open (filename, "R") as fp:
lines = Fp.read () pattern
= Re.compile (r "<=/version=). +? (? =/) ")
Versionlist.append (Re.findall (pattern,lines)) return
versionlist
The same can be done with awk.
PS: Here awk-f Specifies the separator to/. Cut-c the substring of the specified range, 9-Indicates 9 to the end summarize Python's underlying syntax file operations
with open () as lines #with语法可以优雅的打开文件 to ensure that the file is closed and that the exception is caught
For line in lines #读取每行数据. Using text iterators
ReadLines () #将读取文件所有行, returns a list containing each row of data.
ReadLine () #读取一行.
Read () #将文件内容一次性读入内存. String manipulation
Str.find (str) #返回str首字符在查找字符串中的位置, not found return-1
Str.split ('/') #根据指定分隔符分隔字符, return list regular operation
(? <=/version=) said to start with/version=
(? =/) indicated by/end
. +? Represents the shortest matching string ... represents any character, + represents one or more occurrences. Indicates non-greedy match