从文本文件中提取一个步骤,并使用Python放入列表中

问题描述 投票:0回答:3

我正在打开一个txt文件,并将每三个单词分配到一个名为3的列表中。

我以为这可以正确执行,但是我只是将整个文件作为列表。

three=[]

with open('school_prompt.txt', 'r') as f:
    for line in f.split()[::3]:
        three.append(line)
python list slice
3个回答
0
投票

这是简单的方法:

three = []
with open("school_prompt.txt", "r") as f:
    # read the entire file to process
    doc = f.read()
    # split the document
    word_list = doc.split()
    # extract every third word from the document
    three = word_list[::3]

希望对您有帮助!


0
投票

您可以尝试使用enumerate()这样的事情来跟踪计数和想要的每个第三个单词:

three = []
with open('school_prompt.txt', 'r') as f:
   for count, word in enumerate(f, start=1):
      if count % 3 == 0:
        three.append(word)

0
投票

如果文件很大,则可以下一步(它将逐行读取并将每个第三个单词附加到列表中:]

idx = 0
three = []

with open('school_prompt.txt', 'r') as file:
    for line in file:
        for word in line.split():
            idx += 1
            if idx % 3 == 0:
                three.append(word)

print(three) # you list of words on 3rd position
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.