2014-10-26 21 views
1

我有以下格式的文本:閱讀與空白行的文本在Python

In the Grimms' version at least, she had the order from her mother to stay strictly on the path. 
A mean wolf wants to eat the girl and the food in the basket. 

He secretly stalks her behind trees and bushes and shrubs and patches of little grass and patches of tall grass. 

Then the girl arrives, she notices that her grandmother looks very strange. Little Red then says, "What a deep voice you have!" ("The better to greet you with"), "Goodness, what big eyes you have!". 

我想讀它一行行,分裂的話以後使用,我也做了以下內容:

def readFile(): 
    fileO=open("text.txt","r") 
    for line in fileO: 
     word=line.split() 
     for w in word: 
      print w 

問題是它只打印列表中最後一行,但其他行不打印。輸出是這樣的:

['Then', 'the', 'girl', 'arrives,', 'she', 'notices', 'that', 'her', 'grandmother', 'looks', 'very', 'strange.', 'Little', 'Red', 'then', 'says,', '"What', 'a', 'deep', 'voice', 'you', 'have!"', '("The', 'better', 'to', 'greet', 'you', 'with"),', '"Goodness,', 'what', 'big', 'eyes', 'you', 'have!".'] 

重複像n次,我試圖把外部循環以外的字w,但結果是相同的。我錯過了什麼?

+0

檢查通道'爲W的字:打印word'。你當然想要:'對於字w:print w' – michaelmeyer 2014-10-26 20:10:49

回答

2

如果你想的話的線條分割成單獨的列表:

with open(infile) as f: 
    lines = [line.split()for line in f] 
    print(lines) 
[['In', 'the', "Grimms'", 'version', 'at', 'least,', 'she', 'had', 'the', 'order', 'from', 'her', 'mother', 'to', 'stay', 'strictly', 'on', 'the', 'path.'], ['A', 'mean', 'wolf', 'wants', 'to', 'eat', 'the', 'girl', 'and', 'the', 'food', 'in', 'the', 'basket.'], [], ['He', 'secretly', 'stalks', 'her', 'behind', 'trees', 'and', 'bushes', 'and', 'shrubs', 'and', 'patches', 'of', 'little', 'grass', 'and', 'patches', 'of', 'tall', 'grass.'], [], ['Then', 'the', 'girl', 'arrives,', 'she', 'notices', 'that', 'her', 'grandmother', 'looks', 'very', 'strange.', 'Little', 'Red', 'then', 'says,', '"What', 'a', 'deep', 'voice', 'you', 'have!"', '("The', 'better', 'to', 'greet', 'you', 'with"),', '"Goodness,', 'what', 'big', 'eyes', 'you', 'have!"']] 

爲一個單獨的列表使用lines = f.read().split()

+0

謝謝,但是不可能用兩個單獨的for循環來完成嗎? – Layla 2014-10-26 20:14:06

+0

你想列出一個清單還是全部清單? – 2014-10-26 20:14:47

+0

非常感謝! – Layla 2014-10-26 20:15:39