如何让python打印包含大多数单词的行并停止重复打印?
这段代码打印文本文件中的所有行,但是我只需要打印用户输入的包含大多数单词的行。此外,如果未找到用户在中输入的任何单词,则应显示“请重试”,但显示7次您当前正在累积一行包含多少相关单词的计数器,然后将该值保存在其他计数器中并打印该行。相反,您需要计算每行中的单词数,并以最佳结果保存该行,以便在末尾打印如何让python打印包含大多数单词的行并停止重复打印?,python,Python,这段代码打印文本文件中的所有行,但是我只需要打印用户输入的包含大多数单词的行。此外,如果未找到用户在中输入的任何单词,则应显示“请重试”,但显示7次您当前正在累积一行包含多少相关单词的计数器,然后将该值保存在其他计数器中并打印该行。相反,您需要计算每行中的单词数,并以最佳结果保存该行,以便在末尾打印 a=input("Please enter your problem?") problem = a.split(' ') max_num, current_num = 0,0 chosen_lin
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")
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
我没有看到任何代码接近您描述的任务。要停止循环,请使用break。但你不想这样。你不需要在线路上打印任何内容,但是它不打印任何内容。如果我能找到任何单词,我需要它打印“对不起”。这有漏洞,没有解释的尝试。你我的朋友是个天才
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")