运行 csv 文件中的特定行取决于用户输入

run a specific line from a csv file depending on user input

如何根据用户输入 运行 csv 文件中的特定行。 我的代码要求用户输入他们的 phone 问题,如果用户输入 water has spilled 关键字 water or spilled 将被识别并打印存储在 csv 中的解决方案。但是我在那里为不同的关键字存储了许多解决方案。

如果你的problems/solutions是这样写在文件中的:

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 returns Solution1。您只需替换为 keywords/solutions

首先将您的数据集重写为:

'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