python - AttributeError : 'NoneType' object has no attribute 'groups' - re. 搜索

标签 python csv

我正在尝试解析 CSV 文件中一行的前 3 个元素。 CSV文件中的数据如下:

{::[name]str1_str2_str3[0]},1,U0.00 - Sensor1 Not Ready\nTry Again,1,0,12

我想从第一个元素解析 [ ] 中的值 0 或 1。然后是第二个元素中的值。从第三个元素开始,我想解析子字符串“Sensor1 Not Ready”,然后将其转换为大写并将空格替换为下划线(例如 - SENSOR1_NOT_READY)。然后在新列中打印字符串。

正如我之前的一篇 question 中所建议的,

我做了以下 -

import csv
import re

with open('filename.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        tag_name = row[0] # Column A
        bit_num = row[1] # Column B
        error_name = row[2] # Column C

        term0 = '\[(\d)\].*'
        term1 = '(\d+)'
        term2 = '.*-\s([\w\s]+)\\n'

        capture0 = list(re.search(term0, tag_name).groups())
        capture1 = list(re.search(term1, bit_num).groups())
        capture2 = list(re.search(term2, error_name).groups())

当我尝试打印 capture2 时,出现以下错误 -

AttributeError: 'NoneType' object has no attribute 'groups'

谁能解释一下它的含义以及我需要进行哪些修改?

最佳答案

如果 re.search 找不到与您的正则表达式匹配的项,它将返回 None。在尝试调用 .groups() 之前,您应该检查 re.search() 的返回值是否返回结果:

result = re.search(term2, error_name)
capture2 = list(result.groups()) if result else None

关于python - AttributeError : 'NoneType' object has no attribute 'groups' - re. 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940226/

相关文章:

iphone - 如何获取 iPhone 的联系人详细信息并制作该联系人的 CSV 文件

python - 使用 pandas 将字符串对象转换为 int/float

python - 下标序列时Python中的::(双冒号)是什么?

python - Stem Controller 的新身份不改变IP

python - 使用 virtualenv 时以 sudo 身份运行脚本

python - 比较单元格值 csv 文件 python

powershell - 调用ConvertTo-Csv后无法将简单对象保存为CSV

python - 在 Networkx (Python) 中绘制节点值?

python - 在 python 中;将文件列表转换为类似对象的文件

python - 将图像从 float64 转换为 uint8 使图像看起来更暗