在 csv 文件中搜索特定的 str

Search for specific str in a csv file

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

我将电影保存到 csv 文件中。我正在尝试创建一个用户猜测的功能,如果在 csv 中找到电影名称,则打印“恭喜”,否则“再次猜测”。我让它读取文件,但它 return 再次猜测或恭喜文件中的每个字段。我怎么能只 return 一次呢?如果它在任何字段中打印恭喜,或者如果它不在任何字段中则再次猜测但只猜一次。我不想让它按特定行号搜索,因为它可以在任何行中找到。

这是我当前使用的函数,其中引用的 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")

它是 returning:

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

您可以尝试这样的操作:

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

有两个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