在csv文件中搜索指定字符串



我必须创建一个猜谜游戏,每个用户创建一个电影库,然后另一个人必须猜测电影标题。

我将电影保存为csv文件。我试图创建一个功能,其中用户做出猜测,如果电影名称是在csv文件中找到然后打印"恭喜quot;否则"再猜一次"。我让它读取文件,但它再次返回猜测或祝贺文件中的每个字段。我怎么能退一次呢?如果它在任何字段中打印祝贺,或者如果它不在任何字段中,那么再猜一次,但都只有一次。我不想让它按特定的行号搜索,因为它可以在任何行中找到。

这是我当前使用的函数,其中引用的csv文件是其他播放器的电影标题列表。

def guessingPlayer1v3(num_guesses):
for guess in range(0, num_guesses):
Guess=input("Movie title guess: ") #players guess
Guess=Guess.lower().strip() #guess to search for
with open('collection2.csv', 'r') as f_obj:
reader=csv.reader(f_obj, delimiter=',')
for row in reader:
for field in row:
if field == Guess:
print("Congrats, you guessed a title")
else:
print("Guess Again")

返回:

Movie title guess: cat in the hat
Guess Again
Guess Again
Guess Again
Guess Again
Guess Again
Guess Again
Movie title guess: all dogs go to heaven
Guess Again
Guess Again
Guess Again
Congrats, you guessed a title
Guess Again
Guess Again

有两个print语句,第一个确定玩家输入是否正确,第二个显示每一行"Guess Again",撤销else语句并添加return语句将避免这种情况,一旦名称存储在变量上,就迭代所有行并比较它…

for row in reader:
for field in row:
if field == Guess:
print("Congrats, you guessed a title")
return
print("Guess Again") # if movie is not in file

您可以尝试这样做:

import csv
listOfMovies = []
with open('collection2.csv', newline='') as f:
reader = list(csv.reader(f))
for line in reader:
listOfMovies.append(line[0])
def guessingPlayer1v3(num_guesses):
for guess in range(0, num_guesses):
Guess=input("Movie title guess: ").lower().strip() 
if Guess in listOfMovies:
print("Congrats, you guessed a title")
break
else:
print("Guess Again")

相关内容

  • 没有找到相关文章

最新更新