Python扫描string的txt文件,然后写入Excel然后继续下一个匹配

感谢您阅读这首先。 我通常在Perl中编写代码,但是我正在转向Python,我试图用下面的脚本混淆。

我有一个大的文本文件,它具有以下格式…

2014 Apr 11 07:14:03.155 sectorBLAH Interestingcontent Interesting1 = 843 Interesting2 = 56 ReallyInteresting = 1 Interesting3 = N/A 2014 Apr 11 07:14:04.189 sectorBLAH Interestingcontent Interesting1 = 7843 Interesting2 = 656 ReallyInteresting = 0 Interesting3 = 5 

这个顺序持续了一段时间。 我希望做的是创build一个xls文件,这是填充,因为我通过这个长长的名单。 基本上我希望find“ReallyInteresting”string,并捕获它的值“0”或“1”,然后将这个值发送到第2列xls。 同时在xls的第1列中,我希望发布与“ReallyInteresting”string组输出相关的时间戳,有点像这样…

 Column1 07:14:03.155 07:14:04.189 ... Column2 1 0 .... 

我写了下面的代码,但我认为我的行和列正在被覆盖。

 import re import xlwt f = open("C:\Results\Logging.txt", "r") book = xlwt.Workbook(encoding="utf-8") sheet1 = book.add_sheet("New Sheet 1") sheet2 = book.add_sheet("New Sheet 2") searchlines = f.readlines() searchstrings = ['ReallyInteresting ='] timestampline = None timestamp = None f.close() a = 0 tot = 0 row1 = 1 row2 = 1 while a<len(searchstrings): for i, line in enumerate(searchlines): for word in searchstrings: if word in line: timestampline = searchlines[i-4] for l in searchlines[i:i+1]: print timestampline,l, row1 +1 sheet1.write(0, row1, timestampline) for i in line: str = timestampline match = re.search(r'\d{2}:\d{2}:\d{2}.\d{3}', ' ') if match: print '\t',match.group(),'\t',searchstrings[a] row2 +1 sheet2.write(0, row2, searchstrings[a]) print print tot = tot+1 break print 'total count for', '"',searchstrings[a],'"', 'is', tot tot = 0 a = a+1 book.save("New_Excel.xls") 

任何指导将不胜感激。

再次感谢MikG

问题可能在这里:

 row1 +1 

它返回(无处)递增的row1的值,但row1是不变的。

改变它

 row1 += 1 

也适用于row2