2016-11-19 59 views
0
a=input("Please enter your problem?") 
problem = a.split(' ') 
max_num, current_num = 0,0 
chosen_line = '' 

with open('solutions.txt', 'r') as searchfile: 
    for line in searchfile: 
     for word in problem: 
      if word in line: 
       current_num+=1 
     if current_num>max_num: 
      max_num=current_num 
      chosen_line = line 
      print (chosen_line) 
     else: 
      print ("please try again") 

此代碼打印文本文件中的所有行,但我只需要它打印大多數單詞的行,用戶已輸入。此外,如果它沒有找到任何用戶輸入的單詞在它應該顯示「請重試」,但是它顯示其7倍如何讓python用大多數單詞打印行並停止重複打印?

+0

我沒有看到任何代碼逼近您描述的任務。 – TigerhawkT3

+0

要停止循環,請使用'break'。但你不想那樣。你只需要在循環內打印任何東西 –

回答

-1
a=input("Please enter your problem?") 
problem = set(a.split(' ')) 
max_num, current_num = 0,0 
chosen_line = '' 

with open('solutions.txt', 'r') as searchfile: 
    for line in searchfile: 
     current_num = sum(1 for item in line if item in problem) 
     if current_num > max_num: 
      chosen_line = line 
      max_num = current_num 

print chosen_line 
+0

感謝但它不打印任何東西,我也需要它打印'對不起',如果可以找到任何單詞。 –

+1

這有錯誤,並沒有嘗試解釋。 – TigerhawkT3

+0

@ TigerhawkT3我應該如何編寫代碼? –

0

您目前積累的多少相關的字線包含一個計數器,然後保存在不同的計數器值和打印線。相反,您需要在每行中計算單詞並將最佳結果保存在行中,以便最後打印出來。

a = input("Please enter your problem?") 
problem = set(a.split()) 
max_relevance = 0 
best_line = '' 

with open('solutions.txt') as searchfile: 
    for line in searchfile: 
     relevance = sum(word in problem for word in line.split()) 
     if relevance > max_relevance: 
      best_line = line 

print(best_line or "please try again") 
+0

你我的朋友是天才 –