简体   繁体   English

为什么我得到其他所有线路?

[英]Why am I getting every other line?

I am trying to create a Python code for counting the number of words per line of a text. 我正在尝试创建一个Python代码,用于计算文本每行的单词数。

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. 您可以在for循环中逐行迭代文件f But as soon as the next line in the file got read into x , you read the following one into line . 但是,只要将文件中的下一行读入x ,就将以下line读入line As you don't do anything with x , this line gets lost. 由于您对x不执行任何操作,因此此行会丢失。

So, you don't have to use readline() to iterate on the lines of your file. 因此,您不必使用readline()在文件的行上进行迭代。 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. 请注意with open....惯用语,该惯用语可以确保文件关闭,无论脚本中发生什么情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM