在Python中读取带空行的文本

2024-05-26 19:53:12 发布

您现在位置: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次,我试着把for w in单词放在外循环之外,但是结果是一样的。我错过了什么


Tags: andofthetoinyouforhave
1条回答
网友
1楼 · 发布于 2024-05-26 19:53:12

如果要将单词行拆分为单独的列表:

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

相关问题 更多 >

    热门问题