擅长:python、mysql、java
<p>每当您用python编写I/O文件时,我都会使用<code>with</code>(<a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">docs</a>)来提示。另外,迭代每一行,而不是使用<code>inFile.read()</code>。如果你有一个大文件,你的机器内存会感谢你。在</p>
<pre><code>def stats(inF):
num_lines = 0
num_words = 0
num_chars = 0
with open(inF, 'r') as input_file:
for line in input_file:
num_lines += 1
line_words = line.split()
num_words += len(line_words)
for word in line_words:
num_chars += len(word)
print 'line count: %i, word count: %i, character count: %i' % (num_lines, num_words, num_chars)
stats('test.txt')
</code></pre>