所以问题有两个主要部分。 (1) 从每个文件中找出最大值对,(2) 将它们写在 Excel 工作簿中。我一直提倡的一件事是编写可重用的代码。在这里,您必须将所有 xml 文件放在一个文件夹中,然后简单地执行 main 方法并获取结果。
现在有几个选项可以写入 excel。最简单的方法是创建一个制表符或逗号分隔文件 (CSV) 并手动将其导入到 excel 中。 XMWT 是一个标准库。 OpenPyxl 是另一个库,它使创建 excel 文件的代码行数变得更加简单和小。
确保在文件开头导入所需的库和模块。
import re
import os
import openpyxl
在读取 XML 文件时,我们使用正则表达式来提取您想要的值。
regexPatternValue = ">Value\s+(\d+)</content>"
regexPatternAnotherValue = ">Another Value\s+(\d+)</content>"
为了进一步模块化,创建一个方法来解析给定 XML 文件中的每一行,查找正则表达式模式,提取所有值并返回其中的最大值。在下面的方法中,我返回一个包含两个元素 (Value, Another) 的元组,它们是在该文件中看到的每种类型的最大数量。
def get_values(filepath):
values = []
another = []
for line in open(filepath).readlines():
matchValue = re.search(regexPatternValue, line)
matchAnother = re.search(regexPatternAnotherValue, line)
if matchValue:
values.append(int(matchValue.group(1)))
if matchAnother:
another.append(int(matchAnother.group(1)))
# Now we want to calculate highest number in both the lists.
try:
maxVal = max(values)
except:
maxVal = '' # This case will handle if there are NO values at all
try:
maxAnother = max(another)
except:
maxAnother = ''
return maxVal, maxAnother
现在将您的 XML 文件保存在一个文件夹中,对它们进行迭代,然后提取每个中的正则表达式模式。在以下代码中,我将这些提取的值附加到名为 writable_lines 的列表中。最后在解析完所有文件后,创建一个工作簿并以格式添加提取的值。
def process_folder(folder, output_xls_path):
files = [folder+'/'+f for f in os.listdir(folder) if ".txt" in f]
writable_lines = []
writable_lines.append(("Value","Another Value")) # Header in the excel
for file in files:
values = get_values(file)
writable_lines.append((str(values[0]),str(values[1])))
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(len(writable_lines)):
sheet['A' + str(i+1)].value = writable_lines[i][0]
sheet['B' + str(i+1)].value = writable_lines[i][1]
wb.save(output_xls_path)
在较低的 for 循环中,我们指示 openpyxl 将值写入指定的单元格中,例如典型的 excel 格式 sheet["A3"]、sheet["B3"] 等。
准备好了...
if __name__ == '__main__':
process_folder("xmls", "try.xls")