擅长:python、mysql、java
<p>使用<code>collections.Counter()</code>:</p>
<pre><code>from collections import Counter
with open(file) as f:
c = Counter()
for x in f:
c += Counter(x.strip())
</code></pre>
<p>正如@mgilson所指出的,如果文件不是那么大,您可以简单地执行以下操作:</p>
<pre><code>c = Counter(f.read().strip())
</code></pre>
<p>示例:</p>
<pre><code>>>> c = Counter()
>>> c += Counter('aaabbbcccddd eee fff ggg')
>>> c
Counter({'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})
>>> c += Counter('aaabbbccc')
Counter({'a': 6, 'c': 6, 'b': 6, ' ': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})
</code></pre>
<p>或者使用字符串的<code>count()</code>方法:</p>
<pre><code>from string import ascii_lowercase # ascii_lowercase =='abcdefghijklmnopqrstuvwxyz'
with open(file) as f:
text = f.read().strip()
dic = {}
for x in ascii_lowercase:
dic[x] = text.count(x)
</code></pre>