【问题标题】:How to read each line from a file into list word by word in Python如何在Python中逐字将文件中的每一行读入列表
【发布时间】:2014-12-31 13:51:11
【问题描述】:

我正在尝试将行读入一个列表,其中该行上的每个单词都是不同的参数。例如,当我的文本文件包含:

Word1, Word2, Some different words,separated by comma,but no space
Word3, Word4, Some different words,separated by comma,but no space

我想要这样的列表:

['Word1', 'Word2', 'Some different words,separated by comma,but no space'],
['Word3', 'Word4', 'Some different words,separated by comma,but no space']

也许我什至可以得到这样的列表:

['Word1', 'Word2', 'Some different words','separated by comma', 'but no space']

到目前为止,当文本文件中有一行时,我已经通过将每个单词读入列表来完成这项工作。

list_words = f.read().split()

它给了我输出:

['Word1', 'Word2', 'Some different words,separated by comma,but no space']

当我有多行时,我该怎么做?另外,如果我以后想从两个列表中打印出第一个参数,我可以使用 list_words[0] 它会自动给我 'Word1' 和 'Word3' 吗?

我希望这个解释足够清楚。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用以下列表理解

    list_words = [i.split(',') for i in f]
    

    【讨论】:

    • 删除 .readlines() 将使此代码更快、更短,并且还避免一次将整个文件读入内存(即使列表将其保存在内存中)
    • 感谢@Cyber​​!但是我怎样才能从我得到的列表中打印第一个、第二个等单词呢?例如,如果我使用 print list_words[0] 我得到:['Word1', 'Word2', 'Some different words','用逗号分隔','but no space']。但我只想得到'Word1'。如果我使用 print list_words[1] 我得到第二个列表。我可以做类似 list_words[1,1] 或 list_words[1,[1]] 的事情吗?
    • @user3019389 比如你会说print list_words[0][0]
    • @Cyber​​ 非常感谢!!
    【解决方案2】:

    如果你想用逗号和空格分隔,你可以使用re.split:

    >>> with open('f.txt') as f:
    ...   print [re.split(', ',line) for line in f]
    ...
    [['Word1', 'Word2', 'Some different words,separated by comma,but no space\n'],
     ['Word3', 'Word4', 'Some different words,separated by comma,but no space\n']]
    

    如果你想在每个逗号上拆分,只需使用 str.split:

    >>> with open('f.txt') as f:
    ...   print [line.split(',') for line in f]
    ...
    [['Word1', ' Word2', ' Some different words', 'separated by comma', 'but no space\n'],
     ['Word3', ' Word4', ' Some different words', 'separated by comma', 'but no space\n']]
    

    您可以使用strip 摆脱\n

    >>> with open('f.txt') as f:
    ...   print [line.strip().split(',') for line in f]
    ...   # or print [re.split(', ',line.strip()) for line in f]
    ...
    [['Word1', ' Word2', ' Some different words', 'separated by comma', 'but no space'],
     ['Word3', ' Word4', ' Some different words', 'separated by comma', 'but no space']]
    

    其实你也可以使用line.strip().split(', ')。我只是忘了你可以有超过 1 个字符的分隔符......

    【讨论】:

    • 我只是想知道,在这段代码中为什么需要re.split(', ', line) 而不是line.split(', ')
    • @jamylak 因为每次我都忘了 str.split 可以包含多个字符……
    猜你喜欢
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2019-11-11
    • 2012-11-05
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多