【问题标题】:Assign the third word of every line in my file to a list in Python将文件中每一行的第三个单词分配给 Python 中的列表
【发布时间】:2020-07-15 03:14:22
【问题描述】:

我有一个文本文件'news.txt',我试图将每一行的第三个单词保存在一个列表中(三个),我只是不断地得到一个向量,其中包含一行中的第三个单词,它没有'似乎没有在以下几行中注册其他单词。

with open('news.txt', 'r') as file:
    content = file.read()
    words = content.split() 
    for bwords in words:
        three = bwords[2]

【问题讨论】:

  • three = [word[2] for word in words.split()]

标签: python list split


【解决方案1】:
with open('news.txt', 'r') as file:
    content = file.read()
    words = content.split()
    for bwords in words[::3]:
        three = bwords

【讨论】:

  • 这里splitlines会比split更好的选择
【解决方案2】:

我会创建一个迭代器(使用生成器推导),然后将迭代器提供给一个列表。

像这样:

with open('news.txt', 'r') as file:
    # create the iterator using a generator comprehension
    iter_word_3 = (word_list[2] for word_list in 
                   (line.split() for line in file))
    # feed the iterator to the list function
    threes = list(iter_word_3)

您可以选择单独创建生成器函数,而不是使用生成器推导。这样做的好处是,如果没有第三个单词,您可以告诉程序如何处理 IndexError。你甚至可以让它成为一个接受参数的实用函数:

def iter_xth_word(x, filestream):
    """Iterates over xth word from each line of a file."""
    for line in filestream:
        try:
            yield line.split()[x-1]
        except IndexError:
            # ignore lines without a xth word
            continue

with open('news.txt', 'r') as file:
    # create the iterator using a generator comprehension
    iter_word_3 = iter_xth_word(3, file)
    # feed the iterator to the list function
    threes = list(iter_word_3)

【讨论】:

    【解决方案3】:

    您需要在for 循环之前创建一个列表,然后将结果附加到此列表中:

    with open('news.txt', 'r') as file:
        content = file.read()
        words = content.split()
        three = [] 
        for bwords in words:
            three.append(bwords[2])
    

    否则你只会得到循环运行的最后一行的第三个单词。

    或者,您可以使用列表理解来做到这一点:

    three = [word[2] for word in words]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      相关资源
      最近更新 更多