【问题标题】:Python: Importing from text file into sublistsPython:从文本文件导入子列表
【发布时间】:2016-03-08 01:29:59
【问题描述】:

我正在尝试读取一个文本文件并让每一行成为一个子列表,该行的每个单词都是该子列表中的不同条目,例如:
第 1 行你好,我的名字是 bob
第 2 行你好,我的名字是蒂姆
我希望列表类似于:
[[你好,我的名字,是,鲍勃],[你好,我的,名字,是,蒂姆]]
results = [] fileToProcess = open("zodiac.txt", "r") for line in fileToProcess: for word in line.split(): results.append(line.strip().split(',')) print(results)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    你很亲密。只需使用一次拆分,然后使用空格而不是逗号进行拆分。

    results = []
    fileToProcess = open("zodiac.txt", "r")
    for line in fileToProcess:
       results.append(line.strip().split(' '))
    print(results)
    

    我用下面的文本文件在 python3 中尝试过

    Hello my name is Bob
    Hello my name is Tim
    

    得到结果

    [['Hello', 'my', 'name', 'is', 'Bob'], ['Hello', 'my', 'name', 'is', 'Tim']]
    

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 2012-09-04
      • 2013-02-19
      • 2021-09-09
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多