输出结果后出现Python属性错误
我的程序逐行读取文件,并在每一行使用reg ex。 该程序对所有行都执行良好,但在最后抛出以下命令:输出结果后出现Python属性错误,python,python-3.x,Python,Python 3.x,我的程序逐行读取文件,并在每一行使用reg ex。 该程序对所有行都执行良好,但在最后抛出以下命令: Traceback (most recent call last): File "test.py", line 24, in <module> output = pattern.search(line).group() AttributeError: 'NoneType' object has no attribute 'group' 回溯(最近一次呼叫最后一次): 文
Traceback (most recent call last):
File "test.py", line 24, in <module>
output = pattern.search(line).group()
AttributeError: 'NoneType' object has no attribute 'group'
回溯(最近一次呼叫最后一次):
文件“test.py”,第24行,在
输出=模式。搜索(行)。组()
AttributeError:“非类型”对象没有属性“组”
我的代码如下:
import re
pattern = re.compile(r'(?<=\>)(.*?)(?=\|)')
# open input file
input_file = open('input.fas', 'r')
while True:
line = input_file.readline()
if line == '' or line is None:
print('EOF')
break
else:
output = pattern.search(line).group()
print(output)
else:
pattern_match = pattern.search(line)
# check for search first before calling group
if pattern_match:
output = pattern_match.group()
print(output)
重新导入
pattern=re.compile(r'(?)(.*?(=\\)'))
#打开输入文件
input\u file=open('input.fas','r')
尽管如此:
line=input_file.readline()
如果行==''或行为无:
打印('EOF')
打破
其他:
输出=模式。搜索(行)。组()
打印(输出)
根据,搜索
如果字符串中没有与模式匹配的位置,则返回None。
所以,在调用group
之前,您可能需要检查模式搜索是否返回了一些内容。也许你可以试试你的
else
如下所示:
import re
pattern = re.compile(r'(?<=\>)(.*?)(?=\|)')
# open input file
input_file = open('input.fas', 'r')
while True:
line = input_file.readline()
if line == '' or line is None:
print('EOF')
break
else:
output = pattern.search(line).group()
print(output)
else:
pattern_match = pattern.search(line)
# check for search first before calling group
if pattern_match:
output = pattern_match.group()
print(output)
对于上述代码,可能类似于以下内容:
import re
pattern = re.compile(r'(?<=\>)(.*?)(?=\|)')
# open input file
input_file = open('input.fas', 'r')
while True:
line = input_file.readline()
if line == '' or line is None:
print('EOF')
break
else:
pattern_match = pattern.search(line)
# check for search first before calling group
if pattern_match:
output = pattern_match.group()
print(output)
重新导入
pattern=re.compile(r'(?)(.*?(=\\)'))
#打开输入文件
input\u file=open('input.fas','r')
尽管如此:
line=input_file.readline()
如果行==''或行为无:
打印('EOF')
打破
其他:
模式匹配=模式搜索(行)
#在呼叫组之前先检查搜索
如果模式匹配:
输出=模式匹配。组()
打印(输出)
您可以尝试打印图案。搜索(行)
哪个错误显示在None
中。将group
函数调用到None
会出现错误。是的,让我困惑的是最后一行是如何跳过if语句的。每个非空行都将运行搜索。如果搜索与任何内容都不匹配,您将调用None.group()