*编辑 我的目标是打印一个字典(word:count),计算字符列表中的名称出现在行列表中的次数。我尝试更改代码,但它要么将每个不同键的值打印为0,要么打印为1011。这就是我目前所在的位置,打印1011个值。我完全不知所措,只上了几周Python课(使用Python3),如果这毫无意义,我会提前道歉
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()
考虑到这是您的数据:
您可以使用
collections.Counter
:或者只是一个dict并将
words
设置为一个集合,这样就不会在重复的单词上循环:从变量的名称中不清楚它们的函数是什么,但这里有一个通用的解决方案:
假设您有一个
words
个值的列表,您希望对这些值的出现次数进行计数,您可以执行以下操作:然后
counts
成为您想要的字典(如果需要,您可以稍后过滤它以获得特定的值)相关问题 更多 >
编程相关推荐