a=input("Please enter your problem?")
problem= ()
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
if problem in line:
print (line)
Can someone please help me on how to get the keywords from the inputed string by the user. Thanks. I need help on how to look for some of the words the users inputed in to =a and search for them on the textfile and print the line
I assume your keywords is meant to be a list?
Then you use any()
to check if any word out of the keywords is in the line.
a=input("Please enter your problem?")
problem= ['#keywords', 'not', 'sure', 'how']
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
if any(word in line for word in problem):
print (line)
Though, you may want to split()
your line to improve that detection.
Otherwise, you have a
, which stores the user's input, so you can use that.
a=input("Please enter your problem?")
problem= a.split()
Then, again problem
is a list, so you use any()
as before
Or, if you want to check if the entire entered value is in a line, then
if a in line:
print(line)
I am not sure I understood the question but is this what you want?. this will take the line containing the most words from the user input:
problem = a.split(' ')
max_num, current_num = 0,0 #max_num count the maximum apparition of words from the input in the line| current_num count the current number of apparition of words of the user input in the line
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:
print line,max_num,current_num
max_num=current_num
chosen_line = line
current_num = 0
print chosen_line
but it seems to me the easiest way to do what you want is to store at the start of each answer the question, or even easier - just ask the user the question number and return this corresponding answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.