6

Pythonで、テキストファイルを繰り返し処理して、各文字の出現回数をカウントするにはどうすればよいですか?'for x in file'ステートメントを使用してそれを調べてから、26程度のif elifステートメントを設定できることに気付きましたが、それを行うためのより良い方法は確かにありますか?

ありがとう。

4

5 に答える 5

16

使用collections.Counter()

from collections import Counter
with open(file) as f:
    c = Counter()
    for line in f:
        c += Counter(line)

Counterファイルがそれほど大きくない場合は、すべてのファイルを文字列としてメモリに読み込み、1行のコードでオブジェクトに変換できます。

c = Counter(f.read())

例:

>>> 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})

またはcount()文字列のメソッドを使用します。

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)
于 2012-09-09T19:26:59.477 に答える
3

辞書を使う-基本的にletters[char]++

于 2012-09-09T19:26:29.870 に答える
1

このようにして、各文字の辞書ヒストグラムを作成します。これを使用して、棒グラフなどを作成できます。文字またはサブセットに制限する場合は、条件を追加するかfreqs、最後にフィルターをかける必要があります。

freqs = {}
with open('your_filename.txt') as f:
    for line in f:
        for char in line:
            if char in freqs:
                freqs[char] += 1
            else:
                freqs[char] = 1

print(freqs)

次を使用して同じロジックを作成することもできますdict.setdefault

freqs = {}
with open('your_filename.txt') as f:
    for line in f:
        for char in line:
            freqs.setdefault(char, 0)
            freqs[char] += 1

または使用collections.defaultdict

from collections import defaultdict

freqs = defaultdict(int)
with open('your_filename.txt') as f:
    for line in f:
        for char in line:
            freqs[char] += 1
于 2012-09-09T19:40:18.190 に答える
0

Counterはこれを行うための良い方法ですが、Counterは3.1以降と2.7でのみ使用できます。

3.0または2.[56]を使用している場合は、代わりにcollections.defaultdict(int)を使用する必要があります。

于 2012-09-09T19:38:25.150 に答える
0

基本的に、インポートなし:is_letterは、何かが文字であるかどうかを判断する関数であるため、通常の英語の文字以外のものを数えることができます

def add_or_init(dictionary, c):
        if(c in dictionary):
                dictionary[c]+=1
        else:
                dictionary[c]=1
def count_one_letter(dictionary, c, is_letter):
        if is_letter(c):
                add_or_init(dictionary, c)
def count_letters(dictionary, string, is_letter):
        for c in string:
                count_one_letter(dictionary, c, is_letter)
        return dictionary

#count all characters
count_letters(dict(),'aaabbbcccddd eee fff ggg',lambda x: True)
# => {'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3}
于 2012-09-09T19:53:41.540 に答える