私は初心者の 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
私の問題は、テキスト ファイルに複数行のテキストが含まれている場合や句読点がある場合に正しく機能しないことです。