【问题标题】:run a specific line from a csv file depending on user input根据用户输入从 csv 文件运行特定行
【发布时间】:2017-04-01 12:43:34
【问题描述】:

如何根据用户输入运行 csv 文件中的特定行。 我的代码要求用户用他们的手机输入问题,如果用户输入水已经溢出关键字水或溢出将被识别并打印存储在 csv 中的解决方案。但是我为不同的关键字存储了许多解决方案。

【问题讨论】:

  • keywords.txt 中的行在关键字和解决方案之间交替,对吗?此外,我建议使用 json 作为更好的信息存储方式:docs.python.org/3/library/json.html
  • @BurningKarl 你能看看我的其他问题吗
  • @stovfl 你能看看我的其他问题吗
  • @sufiya:没有看到任何其他问题。为什么你删除了你的code,把它找回来。

标签: python csv input keyword


【解决方案1】:

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

'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

【讨论】:

  • 谢谢!!!无论如何,是否可以从句子中检测到关键字“关闭”。当我输入一个包含关键字的句子时,程序不起作用。如果我自己输入,它工作得很好:) @Tasos
  • 很高兴它对您有用!为了处理给定的句子,一个想法是将句子分成单词,然后独立搜索每个单词。您可以将 if problems ... 行替换为 if any(word in line for word in problems.split()):
  • 出现错误。它说问题未定义@Tasos
  • 那么您可能在复制分离时出现拼写错误。这是problems 不是problem :)
  • if any(word in line for word in questions.split()): input("什么是问题?")
【解决方案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。您只需用您的关键字/解决方案替换

【讨论】:

  • 小心你的i += 1。您可以轻松检查 for i, line in enumerate(["a", "b", "c", "d"]): print(i, end=" "); i += 1 是否提供 0 1 2 3 而不是 0 2
  • 对,range函数在这里更合适
  • 请同时更改您的描述,因为在您的描述中阅读i += 1 而没有在实际代码中看到它是令人困惑的。还有liste这里没有定义,改成list_of_problems_and_solutions
  • 抱歉,我这样做了
  • @Guil23 你能看看我的其他问题吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
相关资源
最近更新 更多