<p>使用@Joran Beasley的答案,我提出了以下解决方案,似乎奏效了:</p>
<p><strong>要点:</strong></p>
<ul>
<li>我的日志文件总是遵循相同的结构:{Date}-{Type}-
{消息}所以我使用字符串切片和拆分来将项目分解
需要他们。例如{Date}总是23个字符,而我
想要前19个字符。</li>
<li>使用line.startswith(“2015”)是疯狂的,因为日期最终会改变,所以创建了一个新函数,它使用一些正则表达式来匹配我期望的日期格式。再一次,我的日志日期遵循一个特定的模式,这样我可以得到特定的。</li>
<li>文件被读入第一个函数“generatedits()”,然后调用“matchDate()”函数,查看正在处理的行是否与我正在查找的{Date}格式匹配。</li>
<li>每次找到有效的{Date}格式时都会创建一个新的dict,并在遇到下一个有效的{Date}之前处理所有内容。</li>
</ul>
<h2>函数来拆分日志文件</h2>
<pre><code>def generateDicts(log_fh):
currentDict = {}
for line in log_fh:
if line.startswith(matchDate(line)):
if currentDict:
yield currentDict
currentDict = {"date":line.split("__")[0][:19],"type":line.split("-",5)[3],"text":line.split("-",5)[-1]}
else:
currentDict["text"] += line
yield currentDict
with open("/Users/stevenlevey/Documents/out_folder/out_loyaltybox/log_CardsReport_20150522164636.logs") as f:
listNew= list(generateDicts(f))
</code></pre>
<h2>函数查看正在处理的行是否以与我正在查找的格式匹配的{Date}开头</h2>
<pre><code> def matchDate(line):
matchThis = ""
matched = re.match(r'\d\d\d\d-\d\d-\d\d\ \d\d:\d\d:\d\d',line)
if matched:
#matches a date and adds it to matchThis
matchThis = matched.group()
else:
matchThis = "NONE"
return matchThis
</code></pre>