Python - 在字典中搜索字符串

时间:2016-04-22 21:04:43

标签: python csv dictionary

基本上,我有一个故障排除程序,我希望用户输入他们的输入。然后,我接受此输入并将单词拆分为单独的字符串。之后,我想从.CSV文件的内容创建一个字典,其中键是可识别的关键字,第二列是解决方案。最后,我想检查拆分用户输入中的任何字符串是否在字典键中,打印解决方案。

然而,我面临的问题是我可以做我上面所说的,然而,它会循环通过,如果我的输入是'我的手机是湿的'和'湿&# 39;是一个可识别的关键字,它会通过并说“未识别'”,“无法识别','无法识别'”,最后它会打印解决方案。它说没有被识别太多次,因为字符串'我的','电话'和'是'不被承认。

那么我如何测试用户是否在我的字典中分割输入而没有输出'未识别'等。

对不起,如果不清楚,我对整件事情感到很困惑。

代码:

import csv, easygui as eg
KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
Problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
for Problems, Solutions in (KeywordsCSV.items()):
    pass

注意,我有通行证,因为这是我需要帮助的部分。

我的CSV文件包含:

problemKeyword |溶液

例如;

湿手将手机放入一碗米饭中。

3 个答案:

答案 0 :(得分:1)

只有一个布尔值和一个if循环后才会运行,如果句子中的所有单词都没有被识别出来。

答案 1 :(得分:1)

你的代码看起来像一些丑陋的代码高尔夫球。在我们研究如何解决问题之前,让我们进行清理

import easygui as eg
import csv

# # KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
# why are you nesting THREE function calls? That's awful. Don't do that.
# KeywordsCSV should be named something different, too. `problems` is probably fine.

with open("Keywords and Solutions.csv") as f:
    reader = csv.reader(f)
    problems = dict(reader)

problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
# this one's not bad, but I lowercased your `Problem` because capital-case
# words are idiomatically class names. Chaining this many functions together isn't
# ideal, but for this one-shot case it's not awful.

让我们在这里打破一秒,注意我在代码的每一行都改变了一些东西。尽可能花些时间熟悉PEP8!它将极大地改进您用Python编写的任何代码。

无论如何,一旦你获得了problems字典,并且problem应该是该字典中的关键字,你可以这样做:

if problem in problems:
    solution = problems[problem]

甚至使用dict.get的默认回报:

solution = problems.get(problem)
# if KeyError: solution is None

如果您想循环播放,可以执行以下操作:

while True:
    problem = eg.enterbox(...)  # as above
    solution = problems.get(problem)
    if solution is None:
        # invalid problem, warn the user
    else:
        # display the solution? Do whatever it is you're doing with it and...
        break

答案 2 :(得分:0)

我认为你可以使用类似的东西:

for word in Problem:
    if KeywordsCSV.has_key(word):
        KeywordsCSV.get(word) 

或列表理解:

[KeywordsCSV.get(word) for word in Problem if KeywordsCSV.has_key(word)]