我是 Python 的新手。我需要比较两个单词列表并检测一个列表中不在另一个列表中的那些单词。 这里有两个测试文件
大列表.txt
[coin, co-operate, accurate, achieve, adapt, adjust, admire, admission, enter, advance, adventure, aeroplane, plane, affair, aim, objective, annual, approach, approve, argument]
小列表.txt
[coin, co-operate, football, accurate, achieve, adapt, amazing, adjust, admire, admission, enter, advance, breakfast]
有了这个预期的输出
[football, amazing, breakfast]
我这里有一个非常简单的 Python 脚本
from sys import argv
big_list, small_list = argv
blist = open(big_list).read()
slist = open(small_list).read()
dlist = [item for item in slist if item not in blist]
diff_list = open(dlist, 'w').write()
diff_list.close()
但是运行时返回这个错误信息
roy@medea:~/e2tw/list_comparison$ python file_comp1.py big_list.txt small_list.txt
Traceback (most recent call last):
File "file_comp1.py", line 3, in <module>
big_list, small_list = argv
ValueError: too many values to unpack
请您参考如下方法:
尝试:
big_list, small_list = argv[1:]
为什么?因为三个参数会默认传递给你的脚本,argv[0]是脚本名
附言在你的最后两行中,有一个 bug 等待关闭。您不能将列表作为对文件对象的引用传递。你应该这样做:
output_file = open("filename.txt", "w")
output_file.write("[%s]" % ", ".join(dlist))
output_file.close()
