用Python解析文本文件

用Python解析文本文件,python,Python,我有txt文件,我想学习如何用Python解析txt文件 txt文件: April 2011 05.05.2013 8:30 20:50 (这里我可以有不同的数据) 如何解析此文件并将所有数据放在单独的变量中 示例输出: month = "April 2011" mydate = "05.05.2013" time_start = "8:30" time_stop = "20:50" 输出 April 2011 05.05.2013 8:30 20:50 这里的关键是首先分析您的输入文件格

我有txt文件,我想学习如何用Python解析txt文件

txt文件:

April 2011
05.05.2013 8:30 20:50
(这里我可以有不同的数据)

如何解析此文件并将所有数据放在单独的变量中

示例输出:

month = "April 2011"
mydate = "05.05.2013"
time_start = "8:30"
time_stop = "20:50"
输出

April 2011 05.05.2013 8:30 20:50

这里的关键是首先分析您的输入文件格式以及您想要从中得到什么。让我们考虑一下你的输入数据:

April 2011
05.05.2013 8:30 20:50
我们这里有什么

第一行用空格分隔月份和年份。如果您想将“April 2011”作为一个单独的Python标签(变量)放在一起,您可以使用方法读取整个文件,列表的第一项将是“April 2011”

下一行是日期和两个时间“字段”,每个字段之间用空格分隔。根据您的输出需求,您希望将它们分别放在单独的Python标签(变量)中。所以,仅仅阅读第二行对你来说是不够的。您必须将上面的每个“字段”分开。
split()。以下是一个例子:

>>> s = '05.05.2013 8:30 20:50'
>>> s.split()
['05.05.2013', '8:30', '20:50']
正如您所看到的,现在您已经将字段作为列表的项目进行了分隔。现在,您可以轻松地将它们指定给单独的标签(或变量)

根据您拥有的其他数据,您应该尝试一种类似的方法,首先分析如何从文件的每一行获取所需的数据

文件a.txt

April 2011
05.05.2013 8:30 20:50
May 2011
08.05.2013 8:32 21:51
June 2011
05.06.2013 9:30 23:50
September 2011
05.09.2013 18:30 20:50
python代码

import itertools

my_list = list()
with open('a.txt') as f:
    for line1,line2 in itertools.izip_longest(*[f]*2):
        mydate, time_start, time_stop = line2.split()
        my_list.append({
            'month':line1.strip(),
            'mydate': mydate,
            'time_start': time_start,
            'time_stop': time_stop,
        })

print(my_list)

我现在只知道如何读取文件:+1这是一个非常有用的答案,因为它给出了为什么不只是答案。
April 2011
05.05.2013 8:30 20:50
May 2011
08.05.2013 8:32 21:51
June 2011
05.06.2013 9:30 23:50
September 2011
05.09.2013 18:30 20:50
import itertools

my_list = list()
with open('a.txt') as f:
    for line1,line2 in itertools.izip_longest(*[f]*2):
        mydate, time_start, time_stop = line2.split()
        my_list.append({
            'month':line1.strip(),
            'mydate': mydate,
            'time_start': time_start,
            'time_stop': time_stop,
        })

print(my_list)