Python:如何使用多个分隔符分割逗号、冒号和字母

2024-05-16 08:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的一个数据示例(在我的csv文件中有很多行这样的数据),我需要一个程序来分离连字符、冒号和字母“T”,这样我就可以打印出我想要的日期(例如12月31日)的行。我已经有了一个可以过滤掉年和月的代码,但是我目前在拆分T/设置T作为分隔符时遇到了问题。你知道吗

AC2\ AC1382,32015-12-31T22:40:00-05

import csv

desiredMonth = 12
with open('extractedStreet2015.csv', 'r') as csvfile:
    content = csv.reader(csvfile, delimiter=',')
    for row in content:
        month = int(row[3].split('-')[1])
        if month == desiredMonth:
            print(row)

我怎样才能写一个代码,这样我就可以拆分冒号和字母“T”? (另请注意,我对Python还不太熟悉,因此非常感谢您的解释)

编辑

当我尝试运行以下程序时:

import csv
import isodate

desiredHour = 12

with open('bt_2015.csv', 'r') as csvfile:
    content = csv.reader(csvfile, delimiter=',')
    for row in content:
        date = isodate.parse_datetime(content[3])
        if date.hour == desiredHour:
            print(row[1])

出现以下消息:

Traceback (most recent call last):
  File "C:\Python36\hour.py", line 10, in <module>
    date = isodate.parse_datetime(content[3])
TypeError: '_csv.reader' object is not subscriptable

我能做些什么来解决这个问题?你知道吗


Tags: csv数据csvfile代码inimport程序date
2条回答

以您的例子:

# filename: test_data.txt
AC2_AC1,382,3,2015-12-31T22:40:00-05

这就是我要做的。。。。你知道吗

$ pip install python-dateutil

见:pip

见:namedtuple

见:python-dateutil

#!/usr/bin/env python
# filename: test.py
import csv
from collections import namedtuple

from dateutil import parser

#  I don't know your field names, but maybe you can supply them.
StreetRecord = namedtuple('StreetRecord', 'ac_field, num01, num02, timestamp')


def extract_records(filepath, month):
    """Captures records that match the month

    Args:
        filepath (str): path to file
        month (int): value of month to filter on

    Yields:
        StreetRecord: each street record that matches the month
    """
    with open(filepath, 'r') as stream:
        content = csv.reader(stream, delimiter=',')
        for record_data in content:
            record = StreetRecord(*record_data)
            # example timestamp: 2015-12-31T22:40:00-05
            timestamp = parser.parse(record.timestamp)
            if timestamp.month == month:
                yield record


if __name__ == '__main__':
    for record in extract_records('test_data.txt', 12):
        print(record)

然后运行它。。。你知道吗

python test.py

你会看到:

StreetRecord(ac_field='AC2_AC1', num01='382', num02='3', timestamp='2015-12-31T22:40:00-05')

怎么样

import isodate
data = 'AC2_AC1,382,3,2015-12-31T22:40:00-05'
parts = data.split(',')
isodate.parse_datetime(parts[3])
datetime.datetime(2015, 12, 31, 22, 40, tzinfo=<FixedOffset '-05'>)

现在您有了一个标准的python datetime对象

相关问题 更多 >