我有以下格式的文本:

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放在外部循环之外,但是结果是相同的。我想念什么?

最佳答案

如果您想将单词行分成单独的列表:

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()

关于python - 在Python中读取空白行的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26577340/

10-12 18:11