I am trying to create a Python code for counting the number of words per line of a text.
My text consists of the following movie titles:
We Still Steal the Old Way Demon Immortal Wars The Portal Selfie from Hell The Bad Nun Astro Diggerz: Black Lung Rises Battle Drone How to Train Your Dragon 3
The code I created is as follows:
f = open('C:/movies/sample06.txt')
for x in f:
line = f.readline()
print(line, end='')
words = line.split(" ")
print(words)
num_words = len(words)
print(num_words)
And what I get is:
Demon ['Demon\n'] 1 The Portal ['The', 'Portal\n'] 2 The Bad Nun ['The', 'Bad', 'Nun\n'] 3 Diggerz: Black Lung Rises ['Diggerz:', 'Black', 'Lung', 'Rises\n'] 4 How to Train Your Dragon 3 ['How', 'to', 'Train', 'Your', 'Dragon', '3\n'] 6
My question is: How can I get the results for each and every movie title above? The result here showed the results of every other movie title.
Your code starts with:
f = open('C:/movies/sample06.txt')
for x in f:
line = f.readline()
You iterate on your file f
line by line in the for
loop. But as soon as the next line in the file got read into x
, you read the following one into line
. As you don't do anything with x
, this line gets lost.
So, you don't have to use readline()
to iterate on the lines of your file. Just do:
with open('C:/movies/sample06.txt') as f:
for line in f:
print(line, end='')
words = line.split(" ")
print(words)
num_words = len(words)
print(num_words)
Note the with open....
idiom that guarantees that your file gets closed whatever happens in your script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.