Python,字符串循环后打印出不止一次,虽然我有休息
问题描述:
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()将用户输入转换为数组,但我无法找到一种解决方法。我曾尝试使用'下一个'和'任何'没有成功。有什么建议么?Python,字符串循环后打印出不止一次,虽然我有休息
答
你只需要修改你的代码结构,只是有点和问题解决了:
#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.")
我已经做了如下修改代码:
- 创建一个变种
results
专门跟踪比赛数量。我们在最后两行使用这个var来确定是否打印字符串。当然,你可以使用一个布尔值来找到匹配,并将其设置为true。不过,我选择计算匹配,因为您可能能够在某处使用该信息。 - 将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 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
我认为这可能会有帮助。
+0
感谢您的帮助! –
感谢您的帮助!我已经尝试了这两种方法,如你所描述的,他们的工作。 –