我可以在文件夹中搜索所有版本日志行,但我试图选择列表中的最新版本,但我不知道如何选择,因为列表的元素包含字符和数字。
下面是我的代码,用于查找和创建一个名为matched_lines的列表,其中包含所有说明日志版本号的行。我希望从创建的列表中找到最新版本,并将该最新版本与日志之外的实际最新版本进行比较。例如,生成的列表将包含:
['版本 2.13.1.1', '版本 2.12.1.0', '版本 2.10.1.4']
在这个例子中,我希望选择“Version 2.13.1.1”,并将其与日志中的最新版本号进行比较,例如“Version 2.14.1.0”。
for filename in files:
#print('start parsing... ' + str(datetime.datetime.now()))
matched_line = []
try:
with open(filename, 'r', encoding = 'utf-8') as f:
f = f.readlines()
except:
with open(filename, 'r') as f:
f = f.readlines()
# print('Finished parsing... ' + str(datetime.datetime.now()))
for line in f:
#0strip out \x00 from read content, in case it's encoded differently
line = line.replace('\x00', '')
#regular expressions to fidn the version log lines for each type
RE1 = r'^Version \d.\d+.\d.\d' #Sample regular expression
pattern2 = re.compile('('+RE1+')', re.IGNORECASE)
#for loop that matches all the available version log lines
for match2 in pattern2.finditer(line):
matched_line.append(line)
在此列表中找到最新版本后,我希望将其与可能位于文件夹之外的实际最新版本号进行比较。
首先,您需要从字符串中捕获版本号并将其转换为tuple
of int
形式的(major, minor, micro)
。使用这个作为key
为了max
函数将返回最新版本。
Code
import re
def major_minor_micro(version):
major, minor, micro = re.search('(\d+)\.(\d+)\.(\d+)', version).groups()
return int(major), int(minor), int(micro)
Example
versions = ['Version 2.13.1.1', 'Version 2.12.1.0', 'Version 2.10.1.4']
latest = max(versions, key=major_minor_micro)
print(latest) # 'Version 2.13.1.1'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)