关于文件中.split的Python

时间:2017-08-22 11:20:30

标签: python

大家好,请大家帮帮忙吗?

这是我的txt文件的内容

DICT1 Assignment 1 25 100 nothing anyway at all
DICT2 Assignment 2 25 100 nothing at all
DICT3 Assignment 3 50 100 not at all

这是我的代码

from pathlib import Path
home = str(Path.home())

with open(home + "\\Desktop\\PADS Assignment\\DICT1 Assessment Task.txt", "r") as r:
    for line in r:
       print(line.strip().split())

我的代码输出是

['DICT1', 'Assignment', '1', '25', '100', 'nothing']
['DICT2', 'Assignment', '2', '25', '100', 'nothing', 'at', 'all']
['DICT3', 'Assignment', '3', '50', '100', 'not', 'at', 'all']

现在我的问题是,我如何使输出

['DICT1', 'Assignment 1', '25', '100', 'nothing']
['DICT2', 'Assignment 2', '25', '100', 'nothing at all']
['DICT3', 'Assignment 3', '50', '100', 'not at all']

2 个答案:

答案 0 :(得分:5)

您可以使用maxsplit方法的split参数

line.split(maxsplit=5)

当然,如果文件中的行格式相似,并且您使用的是python 3。

对于Python 2.x,您应该使用

line.split(' ', 5)

答案 1 :(得分:2)

这里的主要问题是您的输入文件,此文件中的分隔符是一个空格,但您也有一些值可以检索空格。

所以你有两个选择:

  1. 您可以将输入文件更改为逗号分隔值,即:

    DICT1, Assignment, 1, 25, 100, nothing anyway at all
    DICT2, Assignment, 2, 25, 100, nothing at all
    DICT3, Assignment, 3, 50, 100, not at all
    
  2. 一旦获得所有其他项目,就更改脚本以手动解压缩行结束:

    from pathlib import Path
    home = str(Path.home())
    
    with open(home + "\\Desktop\\PADS Assignment\\DICT1 Assessment Task.txt", "r") as r:
        for line in r:
            splittedLine = line.strip().split(" ")
            taskId = splittedLine[0]
            taskTitle = splittedLine[1]
            weight = splittedLine[2]
            fullMark = splittedLine[3]
            description = " ".join(splittedLine[4:])
    
            print("taskId: " + taskId + " - taskTitle: " + taskTitle + " - weight: " + weight + " -fullMark: " + fullMark + " - description: " +            description)