【问题标题】:.split() and .append information from .txt file as tuples to a new list.split() 和 .将 .txt 文件中的信息作为元组添加到新列表
【发布时间】:2014-05-09 10:27:53
【问题描述】:

我正在尝试使用 while 循环逐行读取 .txt 文件,在逗号交点处拆分每一行,调用函数将每行的“日期”侧返回到列表,然后附加“任务”侧到列表中的日期时间。

.txt 文件中的示例行:“tutorial signons,28/02/2014”

结果应如下所示:(datetime.datetime(2014, 2, 28, 0, 0), 'tutorial signons')

我目前的代码正在返回: ['t','u','t','o','r','i','a','l','','s','i','g','n ', 'o', 'n', 's', ',', '2', '8', '/', '0', '2', '/', '2', '0', '1', '4', '\n']

日期时间函数:

def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, DATE_FORMAT)
    except ValueError:
        # The date string was invalid
        return None

load_list 函数:

def load_list(filename):
    new_list = []
    f = open("todo.txt", 'rU')
    while 1:
        line = f.readline()
        line.split(',')
        task = line[1:0]
        datetime = as_datetime(line)
        if not line:
            break
        for datetime in line:
            new_list.append(datetime)
        for task in line:
            new_list.append(task)
        return new_list

【问题讨论】:

    标签: python list split append tuples


    【解决方案1】:

    您必须在变量中捕获 line.split(',') 。 split 不会改变原始变量。

    【讨论】:

    • 变量应该类似于:task = line.split(',') 我将如何指定我想从哪一侧获取值?我会使用类似 task = line.split((',')[0:1]) 的东西吗?
    【解决方案2】:

    只有几件事:

    • 由于您的日期始终在右侧,并且您可能希望在命令部分使用逗号,因此请考虑使用rsplit 而不是split。使用rsplit(',', 1) 只会在最后一个逗号处拆分。
    • 将拆分输出捕获到两个新变量。
    • 看起来"todo.txt" 应该是filename 函数的编写方式。
    • 在适当的情况下对文件使用with
    • 我不确定某些较低逻辑的用途。我编写了下面的代码来跳过没有日期或未读日期的行。

    编辑后的版本如下:

    DATE_FORMAT = '%d/%m/%Y'
    import datetime
    def load_list(filename):
        new_list = []
        with open(filename, 'rU') as f:
            for line in f:
                task, date = line.rsplit(',', 1)
                try:
                    # strip removes any extra white space / newlines
                    date = datetime.datetime.strptime(date.strip(), DATE_FORMAT)
                except ValueError:
                    continue # go to next line
                new_list.append((date, task))
        return new_list
    

    这会返回一个元组列表。您可以轻松地遍历它:

    for date, task in load_list('todo.txt'):
        print 'On ' + date.strftime(DATE_FORMAT) + ', do task: ' + task
    

    最后,我通常建议使用csv 模块,因为您的文件看起来像一个csv 文件。如果task 中永远不会有逗号,那么csv.reader() 功能可以替换rsplit

    【讨论】:

    • 非常感谢您的建议,这里的“with”在打开文件时看起来非常有用。此代码运行良好,无需调用 as_datetime 函数。该文件仅包含逗号,因此如果更稳定,我可能会尝试使用 csv.reader() 进行拆分。
    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2019-08-16
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多