*已编辑 我的目标是打印一个字典(word:count),该字典计算来自characters_list的名称出现在line_list中的次数。我尝试更改代码,但它会将每个不同键的值都打印为0或1011。这是我目前在打印1011值的位置。我完全一无所知,只上了几周的Python课程(使用Python 3),如果没有道理,请提前道歉。
characters_list = [
'threepio', 'luke', 'imperial officer', 'vader', 'rebel officer',
'trooper', 'chief pilot', 'captain', 'woman', 'fixer', 'camie',
'biggs', 'deak', 'leia', 'commander', 'second officer', 'owen',
'aunt beru', 'ben', 'tagge', 'motti', 'tarkin', 'bartender',
'creature', 'human', 'han', 'greedo', 'jabba', 'officer cas',
'voice over deathstar intercom', 'gantry officer', 'intercom voice',
'trooper voice', 'first trooper', 'first officer', 'second trooper',
'officer', 'willard', 'dodonna', 'wedge', 'man', 'red leader',
'chief', 'massassi intercom voice', 'red ten', 'red seven', 'porkins',
'red nine', 'red eleven', 'gold leader', 'astro-officer',
'control officer', 'gold two', 'gold five', 'wingman', 'voice',
'technician'
]
line_list = []
with open('/Users/user_name/Documents/SW_EpisodeIV.txt', 'r') as my_file:
for line in my_file:
line_list.append(line)
line_list = [each_string.lower() for each_string in line_list]
my_dict = {}
for x in range(len(line_list)):
x += 1
for i in characters_list:
my_dict[i] = x
print(my_dict)
main()
答案 0 :(得分:1)
不清楚变量的名称是什么,但这是一个通用解决方案:
鉴于您有一个列表words
想要计数的值,您可以执行以下操作:
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
然后counts
成为您想要的字典(以后可以根据需要将其过滤为特定值)。
答案 1 :(得分:0)
考虑到这是您的数据:
words = ['foo', 'bar', 'bak']
words2 = ['foo', 'bar', 'bak', 'foo', 'no']
您可以使用collections.Counter
:
from collections import Counter
occurences = {k: v for k, v in Counter(words2).items() if k in words}
或者只是一个字典,将words
设为一个集合,这样就不会循环出现重复的单词:
occurences = {}
for word in set(words):
occurences[word] = occurences.setdefault(key, 0) + words2.count(word)