如何根据用户输入从csv文件运行特定行。 我的代码要求用户用手机输入问题,如果用户输入的水溢出了关键字water或溢出将被识别,并且将打印存储在csv中的解决方案。但是我在那里为不同的关键字存储了许多解决方案。
答案 0 :(得分:2)
如果您的问题/解决方案以这种方式写入文件:
Problems1\nSolution1\nProblems2\nSolution2
给出:
Problems1
Solution1
Problems2
Solution2
你可以试试这段代码:
problem = input ('What is your problem ? ')
with open ('keywords.txt', 'r') as myfile:
text = myfile.read()
list_of_problems_and_solutions = text.split('\n')
for i in range (0, len(list_of_problems_and_solutions )-1, 2):
if problem in list_of_problems_and_solutions [i]
print (list_of_problems_and_solutions [i + 1])
>>> What is your problem ? Problems1
Solution1
list_of_problems_and_solutions
会像['Problems1', 'Solution1', 'Problems2', 'Solution2' ]
一样
for i in range (0, len(list_of_problems_and_solutions )-1, 2):
函数将遍历从索引0到结尾的列表,步长为2。
如您所见,当我输入Problems1
作为我的问题时,Python返回Solution1
。您只需要替换为您的关键字/解决方案
答案 1 :(得分:2)
首先将数据集重写为:
'turn', 'on', 'off'
put it on charger
'small', 'text'
go on settings.
...
然后搜索问题并打印下一行。
problems = input("What is the problem?")
with open("/path/myfile.csv") as myfile:
file = iter(myfile.readlines())
for line in file:
if any(word in line for word in problems.split()):
print(next(file))
break