繁体   English   中英

Python,String在for循环后被打印了不止一次,尽管我有一个休息

[英]Python, String is printed out more than once after for loop, although I have a break

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”没有成功。 有什么建议么?

您只需要稍微修改一下代码结构即可解决问题:

#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移出循环。 这不是您的问题的一部分,但是我将其包括在内,因为无论用户搜索多少个关键字,它仅读取一次文件都可以极大地提高性能。

另外,根据文件的大小,对循环顺序进行切换(外循环是读取器,内循环是查询)可能会有所帮助,这样可以减少迭代次数。

更好的是,您可以像这样完全放弃双循环:

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.")

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

好吧,如果希望它停止检查,也应该从外部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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM