我打算創建一個python
腳本來計算每個字母在文本文件中出現的次數。因此,如果該文本文件包含Hi there
,輸出會像計算一個字母在python中出現在文本文件中的次數
E is shown 2 times
H is shown 2 times
I is shown 1 time
R is shown 1 time
T is shown 1 time
我試圖獲取此不同的方式,但我正在顯示沒有輸出爲我進行越來越語法錯誤。我試過以下
import collections
import string
def count_letters(example.txt, case_sensitive=False):
with open(example.txt, 'r') as f:
original_text = f.read()
if case_sensitive:
alphabet = string.ascii_letters
text = original_text
else:
alphabet = string.ascii_lowercase
text = original_text.lower()
alphabet_set = set(alphabet)
counts = collections.Counter(c for c in text if c in alphabet_set)
for letter in alphabet:
print(letter, counts[letter])
print("total:", sum(counts.values()))
return counts
而且
def count_letters(example.txt, case_sensitive=False):
alphabet = "abcdefghijlkmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
with open(example.txt, 'r') as f:
text = f.read()
if not case_sensitive:
alpahbet = alphabet[:26]
text = text.lower()
letter_count = {ltr: 0 for ltr in alphabet}
for char in text:
if char in alphabet:
letter_count[char] += 1
for key in sorted(letter_count):
print(key, letter_count[key])
print("total", sum(letter_count()))
我認爲你有** count **賦值的縮進問題。 – vmonteco
@vmonteco腳本? – smitthy
它顯示的語法錯誤是什麼? –