Python,String在for循环后打印出来不止一次,虽然我休息一下

时间:2017-06-19 21:41:06

标签: python string loops csv for-loop

import csv 

def Start():
    query = input("\nWhat is wrong with your mobile device? ").upper().split() 
    keyword = len(query) 

    for i in range(keyword):
        filename = ("Advice.csv")
        with open(filename) as csvfile:
            reader = csv.DictReader(csvfile) 
            for row in reader:
                if query[i] == row['KEYWORDS']:
                    print(row['ADVICE']) 
Start()

如果用户在我的文本文件中输入了一个没有匹配关键字的字符串,我试图让我的程序打印出“不幸的是我们找不到......”字符串。但是,它保持打印的次数与用户输入的字符串中的单词数相同...我相信这是因为我在代码中使用.split()将用户输入转换为数组,但我找不到一种解决方法。我尝试过使用'next'和'any'但没有成功。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您只需稍微修改一下代码结构,问题就会消失:

#I/O
filename = ("Advice.csv")
with open(filename) as csvfile:
    reader = csv.DictReader(csvfile)

#Initial value of results is 0
results = 0 

#Loop through items
for i in range(keyword):
    for row in reader:
        if query[i] == row['KEYWORDS']:
            print(row['ADVICE']) 
            results += 1 #Increment

if not results:  #This is shorthand for if results == 0
    print("Unfortunately we could not find any advice in our database, we recommend calling your supplier or rephrasing your response.")

我对您的代码进行了以下修改:

  1. 创建一个跟踪匹配数量的var results。我们在最后两行中使用此var来确定是否要打印字符串。当然,您可以为此使用布尔值,并在找到匹配项时将其设置为true。但是我选择计算匹配,因为您可以在某处使用该信息。
  2. 将I / O移到循环外部。这不是你问题的一部分,但是我把它包括在内,因为无论用户搜索多少个关键字,它只会在你阅读文件一次时大大提高性能。
  3. 此外,根据文件的大小,切换循环的顺序可能是有益的(外部循环是读取器,内部循环是查询),这会减少迭代次数。

    更好的是,你可以完全放弃双循环:

    if row["KEYWORDS] in query:
        print(row["ADVICE"])
    else:
         print("Unfortunately we could not find any advice in our database, we recommend calling your supplier or rephrasing your response.")
    

    当然,这是一般性建议。由于您没有提供足够的代码,我无法确定它是否可行。但是,请参阅您是否可以在程序中进行类似的工作。

答案 1 :(得分:0)

好吧,如果你想让它停止检查,你也应该退出外部for循环:

for i in range(keyword):
    get_out = False
    filename = ("Advice.csv")
    with open(filename) as csvfile: #Opens the text file 'Advice.csv' as a csvfile
        reader = csv.DictReader(csvfile) #Reads the file.
        for row in reader:
            if query[i] == row['KEYWORDS']:
                print(row['ADVICE']) #Prints advice linked to keywords.
            else:
                print("Unfortunately we could not find any advice in our database, we recommend calling your supplier or rephrasing your response.")
                get_out = True
                break
    if get_out:
        break

我还建议更改循环顺序,因为这样您将打开文件一次,处理速度变快:

filename = ("Advice.csv")
with open(filename) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
    get_out = False
        for i in range(keyword):
            if query[i] == row['KEYWORDS']:
                print(row['ADVICE']) #Prints advice linked to keywords.
            else:
                print("Unfortunately we could not find any advice in our database, we recommend calling your supplier or rephrasing your response.")
                get_out = True
                break
if get_out:
    break

我认为这可能会有所帮助。