簡體   English   中英

python re.search不起作用

[英]Python re.search not working

在下面的代碼中遇到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

我無法找到錯誤所在? 有人可以告訴我錯誤是什么,如何解決?

在您的代碼示例中,正則表達式表達式與您提供的文件示例不匹配。 XYZ之后缺少空白:

  featureName = re.search(r'.*XYZ : +(\S+\d)',' '.join(featureInfo)).group(1)

此外,為避免NoneType錯誤,應在將re.search用作映射鍵之前測試其結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM