比较文件中的两部电影

时间:2019-04-25 22:09:08

标签: python python-3.x

我需要帮助,我觉得自己处在正确的轨道上,但不知道下一步该怎么做。

这里是我到目前为止的内容:

def compareTwoMovies(movie1, movie2):

    file = open("actors.txt", "r")

    lines = file.readlines()

    movies = {}

    actors = set()


    for lines in file:
        actorList = lines.split(",")
        movieTitle = actorList[0]
        movieActors = actorList[1:]

        for movie in file:

            if movie not in movies:
                movies = movies[movie]
                actors.add(movie)

            else:
                actors.add(movie)

从“ actors.txt”文件中读取各行。 对于每一行:    分开看电影和演员。    对于列出的每部电影:

a)如果电影名称尚未输入词典,     将其添加为键,并将actor的SET存储为值。

b)如果电影名称存在于字典中,则将演员名称添加到          一组演员。即到字典中的值。

字典现在准备好了。 处理功能的输入。

词典中的两个输入键都是吗?

a)如果不是,则打印相应的错误消息并退出。

b)如果是,请执行三个“搜索”并打印其结果。

2 个答案:

答案 0 :(得分:0)

我可以看到一些问题。

电影=电影[电影]删除电影的旧价值。您正在寻找像电影[movieTitle] =演员之类的东西。

actors = set()需要在每一行发生。

不需要for movie in file。在文件中每行处理两次会导致奇怪的问题。

if movie not in movies应该使用movieTitle if movieTitle not in movies

您需要逐步完成movieActors中的每个演员。

答案 1 :(得分:0)

def compareTwoMovies(movie1, movie2):

    file = open("actors.txt", "r")

    lines = file.readlines()# not needed

    movies = {}

    actors = set()


    for lines in file:
        actorList = lines.split(",")
        movieTitle = actorList[0]
        movieActors = actorList[1:]

        for movie in file:

            if movie not in movies:
                movies = movies[movie]
                actors.add(movie)

            else:
                actors.add(movie)
        #what is the necessity of two for loop? why not only one?

我建议的代码如下

def Init_movies_tree(tree_file_name):   
    file = open(tree_file_name, 'r')
    movies = {}
    actors = set()        
    for line in file:
        actorList = line.split(",")
        movieTitle = actorList[0]
        movieActors = actorList[1:]
        movies.setdefault(movieTitle, movieActors)
        actors.add(movieTitle)
    return movies


def compareTwoMovies1(movie1, movie2, tree, debug=False):
    if debug:
       print('Movie[1] name:%s, actors:%s\n'%(movie1, tree[movie1]))
       print('Movie[2] name:%s, actors:%s\n'%(movie2, tree[movie2]))
       #print(f'Movie[1] name:{movie1}, actors:{tree[movie1]})
       #print(f'Movie[2] name:{movie2}, actors:{tree[movie2]})
    if (movie1 == movies2) and movie1 in tree:
       return True
    return False


Tree = Init_movies_tree("actors.txt")
v = compareTwoMovies(movie1, movie2, Tree)
print(v)