我正在嘗試編寫一個函數來計算文本文件中的字符數並返回結果。我有以下代碼;在Python中計算字符在文件中
def file_size(filename):
"""Function that counts the number of characters in a file"""
filename = "data.txt"
with open(filename, 'r') as file:
text = file.read()
len_chars = sum(len(word) for word in text)
return len_chars
這似乎在我的IDE中正常工作,當我測試運行它與我創建的文本文件。但是,當我將代碼提交給doctest程序時,我得到一個錯誤,說它總是給出10的輸出。任何幫助?
附上錯誤消息的屏幕截圖 Error screen。
你想統計獨特的字符嗎? –
[計數字符和行從一個文件python 2.7]可能重複(https://stackoverflow.com/questions/14416522/counting-characters-and-lines-from-a-file-python-2-7) – ziMtyth
你每次都計算同樣的東西......'filename =「data.txt」' –