[英]Python re.search not working
Facing nonetypr object error in below code can anyone please help ? 在下面的代码中遇到nonetypr对象错误,有人可以帮忙吗?
from os import listdir
from os.path import isfile, join
import re, os
featureList = {}
featureFileNames = {}
tempList = [f for f in listdir('.') if isfile(join('.', f))]
for fileName in tempList:
fileName = '.' + os.sep + fileName
featureFile = open(fileName, 'r')
featureInfo = featureFile.readlines(-1)
featureFile.close()
featureName = re.search(r'.*XYZ : +(\S+\d)',' '.join(featureInfo)).group(1)
featureList[featureName]=fileName
I do have more than one files are in the below format :
file 1 :
ABC : 123
ASD : 1234
SADF : 2412
XYZ : 123
file2:
ABC : 3234
ASD : 123323
SADF : 12345
XYZ : 1234555
I am unable to get where the error is ? 我无法找到错误所在? can someone please tell me what is the error and how can I solve it ? 有人可以告诉我错误是什么,如何解决?
In your code sample, the regex expression can not match the file examples you gave. 在您的代码示例中,正则表达式表达式与您提供的文件示例不匹配。 There is a missing whitespace after XYZ
: XYZ
之后缺少空白:
featureName = re.search(r'.*XYZ : +(\S+\d)',' '.join(featureInfo)).group(1)
Moreover to avoid NoneType errors, you should test the result of your re.search
before using it as a map key. 此外,为避免NoneType错误,应在将re.search
用作映射键之前测试其结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.