2017-04-05 62 views
-2
file = open(file_variable) 
n = 0 
line = file.readline() 

while line != "": 
    for ch in line: 
     if ch in '.?!': 
      n += 1 
    file.readline() 

return n 

file_variable.close() 

當我在主程序中嘗試打印n時,它不返回任何內容。有人能給我建議我做錯了什麼。我如何閱讀txt文件的工作原理有點糊塗..計算句子的函數

主程序

from functions import sentence_count 

file_variable = 'pelee.txt' 

n = sentence_count(file_variable) 

print(n) 
+0

你從不打印'n'。 – Alexander

+0

我試圖在主要功能中打印n –

+0

向我們展示您的完整代碼。 – Alexander

回答

2

您需要將line變量重新設置該文件的下一行:

while line != "": 
    for ch in line: 
     if ch in '.?!': 
      n += 1 
    line = file.readline() 

我將反過來遍歷像這樣的文件對象的行:

f = open('example.txt', 'r') 

for line in f: 
    if '.' in line or '?' in line or '!' in line: 
     n += 1 

這個窩rks,因爲Python的open()函數返回一個可循環對象(io.TextIOBase),該對象允許您在for循環中導航文件的內容。 iterable返回的每個項目都是文件的下一行。你可以檢查你想在line變量中找到的字符。

+0

是的,這是有效的。謝謝。你能否更詳細地解釋如何在一個for循環中做到這一點? –

+0

如果你在一行中有多個句子,它將不起作用。 – Matthias