2017-07-14 33 views
0

我一直在學習Python,我想寫一個腳本來計算文本中的字符數並計算它們的相對頻率。但首先,我想知道文件的長度。我的意圖是,雖然腳本從一行到一行地統計所有字符,但它會打印當前行和總行數,所以我可以知道要花多少時間。Python 3.6.1:for循環後不執行代碼

我執行了一個簡單的for循環來計算行數,然後另一個for循環來計算字符並將它們放在字典中。但是,當我用第一個for循環運行腳本時,它會提前停止。就我所知,它甚至不會進入循環的第二個循環。如果我刪除這個循環,其餘的代碼就會很好。這是什麼造成的?

請原諒我的代碼。這是很簡單的,但我爲它感到驕傲。

我的代碼:

import string 

fname = input ('Enter a file name: ') 

try: 
    fhand = open(fname) 

except: 
    print ('Cannot open file.') 
    quit() 

#Problematic bit. If this part is present, the script ends abruptly. 
#filelength = 0 
#for lines in fhand: 
# filelength = filelength + 1 

counts = dict() 
currentline = 1 
for line in fhand: 
    if len(line) == 0: continue 
    line = line.translate(str.maketrans('','',string.punctuation)) 
    line = line.translate(str.maketrans('','',string.digits)) 
    line = line.translate(str.maketrans('','',string.whitespace)) 
    line = line.translate(str.maketrans('','',""" '"’‘「」 """)) 
    line = line.lower() 
    index = 0 
    while index < len(line): 
     if line[index] not in counts: 
      counts[line[index]] = 1 
     else: 
      counts[line[index]] += 1 
     index += 1 
    print('Currently at line: ', currentline, 'of', filelength) 
    currentline += 1 

listtosort = list() 
totalcount = 0 

for (char, number) in list(counts.items()): 
    listtosort.append((number,char)) 
    totalcount = totalcount + number 

listtosort.sort(reverse=True) 
for (number, char) in listtosort: 
    frequency = number/totalcount*100 
    print ('Character: %s, count: %d, Frequency: %g' % (char, number, frequency)) 
+1

如果第一個循環存在,它將消耗文件中的所有行,而第二個循環不會讀取任何行。您需要在循環之間執行'fhand.seek(0)'來倒回文件。 – jasonharper

+0

當我試圖計算我從古騰堡計劃得到的傲慢與偏見時,我不得不包含那條線,因爲它會計算統計中的那些引號。他們在其他翻譯中沒有被刪除。這確實是一種臨時解決方案。 –

+0

哦,我現在看到。所以有一個隱藏的計數器跟蹤我在哪一行,然後我必須用fhand.seek(0)重置它。我想我已經意識到它會在每個循環中重置它自己。我不知道,謝謝。 –

回答

0

它看起來不錯,你正在做的方式,但是,模擬你的問題,我下載並保存了古滕貝格教科書。這是一個unicode問題。兩種方法來解決它。打開它作爲二進制文件或添加編碼。因爲它是文字,我會選擇utf-8。

我也建議你用不同的代碼,下面是基本結構,打開它後關閉文件。

filename = "GutenbergBook.txt" 
try: 
    #fhand = open(filename, 'rb') 
    #open read only and utf-8 encoding 
    fhand = open(filename, 'r', encoding = 'utf-8') 
except IOError: 
    print("couldn't find the file") 
else: 
    try: 
     for line in fhand: 
      #put your code here 
      print(line) 
    except: 
     print("Error reading the file") 
finally: 
    fhand.close() 
+0

謝謝。我會記住這些特點。我仍然掌握着開放命令,編碼等等。 –