samedi 2 septembre 2017

simultaneous (for) loops and (if all) for type

Is there a way to collapse these two "for" loops without having to reopen the text file?

hamletlines = []
hamletwords = []

hamlettext = open("hamlet.txt", "r")
for line in hamlettext.read().split('\n'):
    hamletlines.append(line)
hamlettext.closed  

hamlettext = open("hamlet.txt", "r")    
for word in hamlettext.read().split():
    hamletwords.append(word)
hamlettext.closed    

print("There are ", len(hamletlines), "lines and ", len(hamletwords), "words in Hamlet Text.")
print(type(hamletwords))

Next, I'd like to check if all of the types from a given list are strings but it's showing 'bool' object is not iterable

if all(type(hamletwords)=='str'):
    print("all words are strings")
else:
    print("not all words are strings")

Aucun commentaire:

Enregistrer un commentaire