-4
movies = defaultdict(int)
for line in open('trial.txt', "r"):
    user,movie,rating,time = line.rstrip('\n').split('::')
    movies[movie] += 1

对于以下行,总是会出现我不明白的错误:

user, movie, rating,time = line.rstrip('\n').split('::')
ValueError: need more than 1 value to unpack

我总是可以打印出这条线,它真的有 4 个部分有什么问题?谢谢你!

4

1 回答 1

2

您的文件中似乎有空行。您必须跳过它们以避免此错误,或者至少检查要解压缩的值的数量是否正确:

movies = defaultdict(int)
for line in open('trial.txt', "r"):
    values = line.rstrip('\n').split('::')
    if len(values) == 4:
        user,movie,rating,time = values
        movies[movie] += 1
    else:
        print "Non-valid format: %s" % line
于 2013-03-10T04:47:52.660 回答