2015-12-03 159 views
0

這裏是我的代碼計數從文本文件中每行字數在Python

def getInputFile(): 
bad = True 
while bad: 
    try: 
     fileName = input ("Enter file name: ") 
     # Open file for input 
     f = open(fileName, "r") # Note: "r" means open for reading. 
     bad = False 
    except Exception as err: 
     print ("Please enter a valid file name:") 
return f 


lines=0 
wordCount=0 
fileHandler=getInputFile() 


for lineOfText in fileHandler.readlines(): 
    lines += 1 
    print(str(lines),str(lineOfText)) 
    f1=lineOfText.split() 
    wordCount=wordCount+len(f1) 
    print ("Word count:" +str(wordCount)) 

目前,我的程序只計算運行總計字的文本文件,但我希望它僅計算每行字的文件。另外,我希望程序在最後分析文本文件,並打印出諸如「一行中的大多數單詞」和「每行的平均單詞」等內容,但我無法使用當前的格式進行操作。任何幫助將不勝感激。

+0

您正在執行累計加法操作'wordCount = wordCount + len(f1)'..當然您會在最後得到總計 –

+0

另請參閱:[計算文本文件中的行數,字數和字符數使用Python](http://stackoverflow.com/questions/4783899/counting-lines-words-and-characters-within-a-text-file-using-python) –

回答

1

就快,只需要添加幾件事情:

lines=0 
wordCount=0 
mostWordsInLine = 0 
fileHandler=getInputFile() 


for lineOfText in fileHandler.readlines(): 
    lines += 1 
    print(str(lines),str(lineOfText)) 
    f1=lineOfText.split() 
    wordCount=wordCount+len(f1) 
    if len(f1) > mostWordsInLine: 
     mostWordsInLine = len(f1) 
    print ("Word count:" +str(wordCount)) 

print "Average words per line: {}".format(wordCount/lines) 
print "Most words in a single line: {}".format(mostWordsInLine) 

編輯:爲了打印出每行字的#,你可以更改for循環內的print聲明。

目前你在做print ("Word count:" +str(wordCount)),它打印出累計總數。只需將其更改爲print 'Word count: {}'.format(len(f1))

+0

謝謝,但我仍然無法計算每行中的單詞;它仍然只是保持累計總數。 –

+0

@AButler - 如果你想保留每一行的字數統計記錄,你最好用下面答案中的解決方案。 – TigerhawkT3

+0

@AButler編輯回覆以解決該情況。 – dursk

1

創建list出來的:

result = [len(line.split()) for line in fileHandler] 

然後你可以找到總字數:

print(sum(result)) 

字數每行:

print(*result, sep='\n') 

最高字數:

print(max(result)) 

平均字數:

print(sum(result)/len(result)) 

如果你也想保存每一行,先讀:

lines = fileHandler.readlines() 

然後算的話:

result = [len(line.split()) for line in lines] 

然後zip()這兩個list s:

print(*('{} -- {}'.format(*item) for item in zip(lines, results)), sep='\n') 
+0

我感謝幫助。打印出每行後,是否有任何方法可以打印每行的字數? –

+0

@AButler - 你應該保存文件內容,然後,如我編輯的答案中所示。 – TigerhawkT3

+0

因爲'split'默認情況下會在空白處分裂,所以不會精確計算單詞。例如'some-sentence'會導致長度爲3. –

相關問題