需要超过1个值来解压缩

时间:2013-03-10 04:38:57

标签: python

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个部分 怎么了?谢谢!

1 个答案:

答案 0 :(得分: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