5

私は初心者の python プログラマーで、テキスト ファイル内の文字数を数えるプログラムを作成しようとしています。これが私がこれまでに得たものです:

import string 
text = open('text.txt')
letters = string.ascii_lowercase
for i in text:
  text_lower = i.lower()
  text_nospace = text_lower.replace(" ", "")
  text_nopunctuation = text_nospace.strip(string.punctuation)
  for a in letters:
    if a in text_nopunctuation:
      num = text_nopunctuation.count(a)
      print(a, num)

テキスト ファイルに が含まれている場合hello bob、出力は次のようになります。

b 2
e 1
h 1
l 2
o 2

私の問題は、テキスト ファイルに複数行のテキストが含まれている場合や句読点がある場合に正しく機能しないことです。

4

8 に答える 8

1

re の使用:

import re

context, m = 'some file to search or text', {}
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(len(letters)):
  m[letters[i]] = len(re.findall('{0}'.format(letters[i]), context))
  print '{0} -> {1}'.format(letters[i], m[letters[i]])

それにもかかわらず、カウンターを使用すると、はるかにエレガントでクリーンになります。

于 2013-09-06T00:29:43.337 に答える
1

完全を期すために、を使用せずに実行したい場合は、リスト内包表記と組み込みCounterを使用する別の非常に短い方法を次に示します。dict

from string import ascii_lowercase as letters
with open("text.txt") as f:
    text = f.read().lower()
    print dict((l, text.count(l)) for l in letters)

f.read()ファイル全体の内容をtext変数に読み込みます (ファイルが非常に大きい場合は、悪い考えかもしれません)。次に、リスト内包表記を使用してタプルのリストを作成し、(letter, count in text)このタプルのリストを辞書に変換します。Python 2.7+ では{l: text.count(l) for l in letters}、さらに短くて読みやすい も使用できます。

ただし、これはテキストを複数回 (文字ごとに 1 回) 検索することに注意してください。一方、Counterスキャンは 1 回だけで、一度にすべての文字のカウントを更新します。

于 2013-09-06T08:40:51.010 に答える
1

使用する必要がありますcollections.Counter

from collections import Counter
text = 'aaaaabbbbbccccc'
c = Counter(text)
print c

それは印刷します:

Counter({'a': 5, 'c': 5, 'b': 5})

変数は次のtextようにする必要があります。

import string
text = open('text.txt').read()
# Filter all characters that are not letters.
text = filter(lambda x: x in string.letters, text.lower())

必要な出力を取得するには:

for letter, repetitions in c.iteritems():
    print letter, repetitions

私の例では、次のように出力されます。

a 5
c 5
b 5

詳細については、カウンター ドキュメント

于 2013-09-05T23:52:32.243 に答える
1
import string
fp=open('text.txt','r')
file_list=fp.readlines()
print file_list
freqs = {}
for line in file_list:
    line = filter(lambda x: x in string.letters, line.lower())
    for char in line:
        if char in freqs:
            freqs[char] += 1
        else:
            freqs[char] = 1

print freqs
于 2013-09-06T05:53:18.030 に答える
0

問題を 2 つの単純なタスクに分割できます。

#!/usr/bin/env python
import fileinput # accept input from stdin and/or files specified at command-line
from collections import Counter
from itertools import chain
from string import ascii_lowercase

# 1. count frequencies of all characters (bytes on Python 2)
freq = Counter(chain.from_iterable(fileinput.input())) # read one line at a time

# 2. print frequencies of ascii letters
for c in ascii_lowercase:
     n = freq[c] + freq[c.upper()] # merge lower- and upper-case occurrences
     if n != 0:
        print(c, n)
于 2013-09-06T11:41:37.057 に答える
-1
import sys

def main():
    try:
         fileCountAllLetters = file(sys.argv[1], 'r')
         print "Count all your letters: ", len(fileCountAllLetters.read())
    except IndexError:
         print "You forget add file in argument!"
    except IOError:
         print "File like this not your folder!"

main()

python file.py countlettersfile.txt

于 2019-04-27T18:15:39.367 に答える