我制作了一个小程序,用于搜索1975年NYT畅销书排行榜的标题 - >今天。它工作得很好,但我试图在他们搜索的单词中添加一条消息是找不到的。在下面的脚本中,如果没有结果,用户将获得一个空行。我无法弄清楚如何做到这一点。
在底部的第六行,我试图添加此代码:
if title(s) == None:
print "Sorry, your search gave no results."
但这不起作用。如果没有结果,我可以设置什么条件使程序打印错误消息?
以下是输入文件的示例:
1876 Gore Vidal Random House 4/11/1976 Fiction
23337 Stephen King Scribner 11/27/2011 Fiction
1st to Die James Patterson Little, Brown 3/25/2001 Fiction
2nd Chance James Patterson Little, Brown 3/24/2002 Fiction
3rd Degree James Patterson Little, Brown 3/21/2004 Fiction
4th of July James Patterson Little, Brown 5/22/2005 Fiction
该计划:
def title(s):
f = open("bestsellers.txt", 'r')
for line in f:
list = line.split("\t")
title = list[0]
author = list[1]
date = list[3]
joinList = "".join(title)
cleanList = joinList.lower()
if s in cleanList:
print " %s, by %s (%s)" % (title, author, date)
return
while True:
print "\n"
print "What would you like to do?"
print "1: Search for title"
print "Q: Quit"
choice = raw_input(">")
if choice == "q":
print "Thank you come again"
break
elif choice == "1":
while True:
s_input = raw_input("Enter a title (or part of a title): ")
s = s_input.lower()
title(s)
break
else:
print "Invalid choice. Please try again.\n"
continue
答案 0 :(得分:0)
试试这个:
def title(s):
f = open("bestsellers.txt", 'r')
count = 0
for line in f:
list = line.split("\t")
title = list[0]
author = list[1]
date = list[3]
joinList = "".join(title)
cleanList = joinList.lower()
if s in cleanList:
count = 1
print " %s, by %s (%s)" % (title, author, date)
if count == 0:
print "Sorry, your search gave no results."
return