属性错误:NoneType没有'group'属性
Traceback (most recent call last):
File "redact.py", line 100, in <module>
match = int(re.match(r'\d+', number).group())
AttributeError: 'NoneType' object has no attribute 'group'
输入的数据是这样的: (1, 2)(5, 2)(14, 2)(17, 2)(1, 3)(5, 3)(14, 3)(17, 3)(1, 4)(5, 4)(8, 4)(9, 4)(10, 4)(11, 4)(14, 4)(17, 4)(20, 4)(21, 4)(22, 4)(23, 4)(1, 5)(2, 5)(3, 5)(4, 5)(5, 5)(8, 5)(9, 5)(10, 5)(11, 5)(14, 5)(17, 5)(20, 5)(21, 5)(22, 5)(23, 5)(1, 6)(5, 6)(8, 6)(9, 6)(10, 6)(11, 6)(14, 6)(17, 6)(20, 6)(23, 6)(1, 7)(5, 7)(8, 7)(9, 7)(14, 7)(17, 7)(20, 7)(21, 7)(22, 7)(23, 7)(1, 8)(5, 8)(8, 8)(9, 8)(10, 8)(11, 8)(14, 8)(17, 8)(20, 8)(21, 8)(22, 8)(23, 8)
输出结果是:>>>错误信息 这是我在执行以下代码后得到的错误信息:
xcoord = []
regex = ur"\b[0-9,]{1,}[,]\s\b" #regex for x coordinates
result = re.findall(regex,str1)
for number in result: #get x numbers from coordinate
match = int(re.match(r'\d+', number).group())
xcoord.append(match) #now got array of numbers for x
maxValueX = max(xcoord) #biggest x value
ycoord = []
regex = ur"\b[,]\s[0-9,]{1,}\b" #regex for y coordinates
result = re.findall(regex,str1)
for number in result: #get y numbers from coordinate
match = int(re.match(r'\d+', number).group())
ycoord.append(match) #now got array of numbers for y
maxValueY = max(ycoord) #biggest y value
print maxValueX
print maxValueY
它正在搜索的字符串是:"5', ', 5', ', 6', ', 3',”。在两个不同的在线正则表达式生成器上,上面的正则表达式在这个字符串上运行得很好。为什么它在X坐标上能正常工作,但在Y坐标上却不行?代码完全一样啊!
(顺便说一下,我是想从这个字符串中提取整数)。
谢谢
3 个回答
变量 str1
的内容是什么呢?
re.match(r'\d+', number)
返回 None
是因为 number
和你的正则表达式不匹配,建议你检查一下变量 result
的内容,它是依赖于 str1
的。
每个正则表达式都需要一步一步地测试,可以试试一些正则表达式在线工具,比如 这个 来进行测试。
把你的正则表达式改成: regex = "\b([0-9]+)\,\s\b"
这段代码会创建两个列表,一个包含所有的第一个元素,另一个包含所有的第二个元素。
x_cord = map(int,re.findall("(?<=\()\d+",str1))
y_cord= map(int,re.findall("(?<=\,\s)\d+",str1))
x_cord
[8, 9, 10, 11, 14, 17, 20, 21, 22, 23, 1, 5, 8, 9, 10, 11, 14, 17, 20, 23, 1, 5, 8, 9, 14, 17, 20, 21, 22, 23, 1, 5, 8, 9, 10, 11, 14, 17, 20, 21, 22, 23]
y_cord
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
不需要正则表达式:
str1 = "(8, 5)(9, 5)(10, 5)(11, 5)(14, 5)(17, 5)(20, 5)(21, 5)(22, 5)(23, 5)(1, 6)(5, 6)(8, 6)(9, 6)(10, 6)(11, 6)(14, 6)(17, 6)(20, 6)(23, 6)(1, 7)(5, 7)(8, 7)(9, 7)(14, 7)(17, 7)(20, 7)(21, 7)(22, 7)(23, 7)(1, 8)(5, 8)(8, 8)(9, 8)(10, 8)(11, 8)(14, 8)(17, 8)(20, 8)(21, 8)(22, 8)(23, 8)"
xcoord = [int(element.split(",")[0].strip()) for element in str1[1:-1].split(")(")]
ycoord = [int(element.split(",")[1].strip()) for element in str1[1:-1].split(")(")]
maxValueX = max(xcoord); maxValueY = max(ycoord)
print maxValueX;
print maxValueY;