簡體   English   中英

為什么我得到其他所有線路?

[英]Why am I getting every other line?

我正在嘗試創建一個Python代碼,用於計算文本每行的單詞數。

我的文字包括以下電影標題:

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

我創建的代碼如下:

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)

我得到的是:

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

我的問題是:如何獲得上面每個電影標題的結果? 這里的結果顯示了其他所有電影標題的結果。

您的代碼以以下內容開頭:

f = open('C:/movies/sample06.txt') 
for x in f: 
    line = f.readline()

您可以在for循環中逐行迭代文件f 但是,只要將文件中的下一行讀入x ,就將以下line讀入line 由於您對x不執行任何操作,因此此行會丟失。

因此,您不必使用readline()在文件的行上進行迭代。 做就是了:

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)

請注意with open....慣用語,該慣用語可以確保文件關閉,無論腳本中發生什么情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM