Finding the frequency of some words in a text file

So I want to find the number of times certain characters’ names appear in my text file which therefore indicates who have the most speech, this is my code:

dict_4 = {}
characters_1 = ('(SATURNINUS','BASSIANUS','TITUS ANDRONICUS','MARCUS ANDRONICUS','LUCIUS','QUINTUS','MUTIUS','Young LUCIUS','PUBLIUS','SEMPRONIUS','CAIUS','VALENTINE')
characters_2 = ('AEMILIUS','ALARBUS','DEMETRIUS','CHIRON','AARON','Captain','Tribune','Messenger','Clown')
characters_3 = ('Romans','Goths','TAMORA','LAVINIA','A Nurse','Senators, Tribunes, Officers, Soldiers, anAttendants.')
characters = characters_1 + characters_2 + characters_3
#Here I have made a list of all my characters 
opening = open('file2.txt','r').read()
for word in opening and word in characters:
    if word in dict_4:
        dict_4[word] +=1
    else:
        dict_4[word] = 1
            
print(dict_4)

However I get the error that TypeError: 'bool' object is not iterable on the for word in opening and word in characters: line.
Before, it wasn’t creating a dictionary. Is there anyone who could offer some advice please?

The for word in opening and word in character is associating for word in (opening and word in character), where (opening and word in character) gives a bool.

You could do

from itertools import chain 

for word in chain(opening, character)

if your intention is to iterate over all elements of opening and all elements of character.


On the other hand, that doesn’t solve the original problem that you want to solve.

You could initialize the keys of dict_4 with al the names in character. For example dict_4 = {_: 0 for _ in character}

Afterwards, you could go word by word in opening, and if and only if the word is in dict_4 you increase the value.

for word in opening.split():
    if word in dict_4:
         dict_4[word] += 1
from collections import Counter
dict_4 = Counter(word for line in open('file2.txt') for word in                                                              
                 line.split() if word in characters)