我的文字格式如下:
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次,我试图在外循环外面输入for w,但结果是一样的。我错过了什么?
答案 0 :(得分: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()