Iam使用python从给定字符串中提取某些值。这是我的弦:
mystring.txt
sometext
somemore text here
some other text
course: course1
Id Name marks
____________________________________________________
1 student1 65
2 student2 75
3 MyName 69
4 student4 43
course: course2
Id Name marks
____________________________________________________
1 student1 84
2 student2 73
8 student7 99
4 student4 32
course: course4
Id Name marks
____________________________________________________
1 student1 97
3 MyName 60
8 student6 82我需要提取特定学生的课程名称和相应的分数。例如,我需要上面字符串中的MyName的课程和分数。
我试过:
re.findall(".*?course: (\w+).*?MyName\s+(\d+).*?",buff,re.DOTALL)但是,只有当MyName出现在每门课程下,而在某些课程中缺少MyName (如我的示例字符串)时,这才能起作用。
在这里,我得到的输出为:[('course1', '69'), ('course2', '60')]
但实际上我想要实现的是:[('course1', '69'), ('course4', '60')]
正确的准则是什么?
#!/usr/bin/python
import re
buffer_fp = open("mystring.txt","r+")
buff = buffer_fp.read()
buffer_fp.close()
print re.findall(".*?course: (\w+).*?MyName\s+(\d+).*?",buff,re.DOTALL)发布于 2015-06-03 06:31:27
.*?course: (\w+)(?:(?!\bcourse\b).)*MyName\s+(\d+).*?
^^^^^^^^^^^^您可以尝试使用基于查找的量词this.See demo.Just,该量词将在course之前搜索MyName。
发布于 2015-06-03 06:47:14
我怀疑这在一个正则表达式中是不可能做到的。他们并不是万能的。
即使你找到了办法,也不要这样做。您的非工作正则表达式已接近不可读;工作解决方案可能更难读。您很可能只需几行有意义的代码就可以做到这一点。伪码解决方案:
for line in buff:
if it is a course line:
set the course variable
if it is a MyName line:
add (course, marks) to the list of matches请注意,这可能(而且很可能应该)涉及每个if块中的regexes。这不是在锤子和螺丝刀之间进行选择的情况,而不是将它们排除在外,而是使用它们来做它们最擅长的事情。
https://stackoverflow.com/questions/30612363
复制相似问题