[英]AttributeError: 'NoneType' object has no attribute 'group'
I have to assimilate some data. 我必须吸收一些数据。 The scripts already exist but need to be adjusted to the new data.
脚本已经存在,但需要针对新数据进行调整。
So there is a line: 所以有一行:
head = fn.replace(re.search(r'\d{8}_\d{4}', fn).group(),'')
where I get the Error: AttributeError: 'NoneType' object has no attribute 'group'
我在哪里得到错误:
AttributeError: 'NoneType' object has no attribute 'group'
To fix this I need to understand whats actually is going on at this line. 要解决此问题,我需要了解此行实际发生的情况。
And I do not understand what is done after the "replace". 而且我不了解“替换”之后要做什么。 Can someone explain me whats going on here?
有人可以解释一下这是怎么回事吗? What does
r'\\d{8}_\\d{4}'
mean? r'\\d{8}_\\d{4}'
是什么意思?
re.search is finding matches of your regex pattern and returns a regex match object. re.search正在查找您的正则表达式模式的匹配项,并返回一个正则表达式匹配对象。 If there are no matches it returns None.
如果没有匹配项,则返回None。 So You can't call
.group()
on None. 因此,您无法在None上调用
.group()
。
In [38]: re.search(r'921', mystr)
Out[38]: <_sre.SRE_Match object; span=(23, 26), match='921'>
In [39]: mystr
Out[39]: "b'la lala 135\\r\\n 1039 921\\r\\n'"
In [40]: re.search(r'921', mystr)
Out[40]: <_sre.SRE_Match object; span=(23, 26), match='921'>
In [41]: re.search(r'potatoes', mystr)
The SRE_Match
object has the group()
method which gets the string value of the match. SRE_Match
对象具有group()
方法,该方法获取匹配的字符串值。
In [42]: re.search(r'921', mystr).group()
Out[42]: '921'
So, if you're still not clear what it's all doing, it's finding the string fn
that matches the regex pattern provided in re.search()
and removes it from the string fn
by replacing it with ''
. 因此,如果您仍然不清楚它在做什么,它会找到与
re.search()
提供的正则表达式模式匹配的字符串fn
,并通过将其替换为''
将其从字符串fn
删除。 In this case it's finding matches in fn
that have 8 digits( \\d{8}
) followed by an underscore and then 4 more digits( \\d{4}
). 在这种情况下,它将找到
fn
中具有8位数字( \\d{8}
)和下划线然后再有4位数字( \\d{4}
)的匹配项。 so strings that look like 12345678_1234
. 所以看起来像
12345678_1234
字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.