你怎么让python打印出大多数单词的行并停止重复打印?

时间:2016-11-19 15:43:40

标签: python

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次

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:-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