首页 > 解决方案 > 我在从 csv 日期列中的日期打印指定的正则表达式组时遇到问题 - 类型错误 - Python

问题描述

摘要:我正在尝试使用正则表达式组从 csv 文件的 Date 列中的所有日期返回年份,但得到 TypeError 作为响应。

csv 文件标题:姓名、姓氏、职位、日期日期格式:'2012-02-19'

file = csv.reader(csvfile, delimiter=',')
    for row in file:
        x = row[3].strip()
        result = re.search(r'([0-9]{4})-([0-9]{2})-([0-9]{2})',x)
        print(result[1])


TypeError: 'NoneType' object is not subscriptable 


Expected result : 
2012
2013
2019
2020


Notes: 

# 1) Code above - Performed a check on type returned, type 'str' was correct.
x = row[3].strip()
print(type(x))

<class 'str'>

# 2) Checked my regex match, year 2012 was correctly printed
x = '2012-02-19'

result = re.search(r"([0-9]{4})-([0-9]{2})-([0-9]{2})",x)
print(result[1])

2012

# 3) Results of print(result)
<re.Match object; span=(0, 10), match='2012-05-04'>
<re.Match object; span=(0, 10), match='2013-05-15'>
<re.Match object; span=(0, 10), match='2019-03-13'>
<re.Match object; span=(0, 10), match='2020-03-13'>

标签: python-3.x

解决方案


推荐阅读