擅长:python、mysql、java
<p>这比您所做的要简单,而且在Python中也非常简单:</p>
<pre><code>with open('/var/log/messages', 'r') as f:
cumulative_months = {}
for line in f:
key = line.split()[0].lower()
cumulative_months[key] = cumulative_months.get(key, 0) + 1
</code></pre>
<p><code>with</code>类似于C的<code>using</code>,当文件超出作用域时将关闭它。python文件对象可以用作迭代器。它将一次读取并返回一行,直到到达EOF为止。(它实际上读取的内容不止一行,请参见<a href="https://docs.python.org/2/library/stdtypes.html#file-objects" rel="nofollow">documentation</a>)。在</p>
<p>或者,正如m.wasowski所指出的,您可以将<code>collections.Counter</code>类用于这种类型的任务,以使事情变得更简单、更快。在</p>