2
继this question之后,我开始考虑在字符串中添加更多的层次。例如,这是我的字符串:Python:正则表达式findall子类?
sometext
somemore text here
some other text
course: course1
some details
TestName: test1
some other details
Id Name marks
____________________________________________________
1 student1 65
2 student2 75
3 MyName 69
4 student4 43
some details
TestName: test3
some other details
Id Name marks
____________________________________________________
1 student1 23
3 MyName 63
4 student4 64
course: course2
some details
TestName: test2
some other details
Id Name marks
____________________________________________________
1 student1 84
2 student3 73
some details
TestName: test5
some other details
Id Name marks
____________________________________________________
1 MyName 84
2 student2 73
course: course4
some details
TestName: test1
some other details
Id Name marks
____________________________________________________
1 student1 58
2 student3 89
some details
TestName: test2
some other details
Id Name marks
____________________________________________________
1 student1 97
3 MyName 60
8 student6 82
我想了解MyName
的详细信息。像(course1,test1,69),(course1,test3,63),(course2,test5,84),(course4,test2,60)
或类似输出的输出。
我无法做到在一个单一的步骤,因此想出了这个:
import re
eachcourse = re.split(r'course: \w+',string1)
courselist = re.findall(r'course: (\w+)',string1)
li =[]
for i,course in enumerate(courselist):
match = re.findall(r".*?TestName: (\w+)(?:(?!\TestName\b).)*MyName\s+(\d+).*?",eachcourse[i+1],re.DOTALL)
li.append((course,match))
print li
这给了我
[('course1', [('test1', '69'), ('test3', '63')]), ('course2', [('test5', '84')]), ('course4', [('test2', '60')])]
是否还有更好的和更清洁的方式?
谢谢。
精彩!!非常感谢!只是,还有一个疑问。当Iam使用非常大的字符串时,这种方式是否可取?说25页长的数据? 我注意到返回结果所花费的时间取决于字符串的长度以及字符串中MyName的出现次数。基于MyName For Eg的出现次数,它从0.05秒到50秒不等。在25页的字符串中出现18次需要0.05秒,1次出现需要50.2秒。只需要建议这是否是最好的方法? – Deepa
@Deepa这应该工作,但正则表达式通常不会给出好的性能。最佳方法可以解析通过CSV或其他解析器:) – vks
哦好吧谢谢!请再说一次。假设我需要检索两个学生的详细信息,那么我需要重复这个第二个名字的权利? – Deepa