党校考试--正则匹配答案-YZU

前端之家收集整理的这篇文章主要介绍了党校考试--正则匹配答案-YZU前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

扬大又来党校考试了, 迄今我已经考了三次了。

这次用python写了个,题目与答案中正则匹配出来,字符编码为utf-8,颜色打印使用unix终端格式,所以并不能

正常在win下使用,建议用linux, 如果在win下使用会乱码,会是这么个样子,看清答案有困难。


首先有三个文件,py脚本,答案txt,以及考试页面源码html(在登录党校考试后,点击立即考试时按住ctrl键就能在新标签页打开,然后点击chrome菜单里‘’将页面存储为‘’,即得到一个html页面源码和一个用不到的保存了页面js的文件夹)。


准备好的三个文件,答案txt,页面html与py脚本


py代码如下:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. import re
  5. import sys
  6.  
  7. logo = '''
  8. +-------------------------------------+
  9. | +
  10. | Author: chenjie +
  11. | +
  12. | Date: 2014/10/13 +
  13. | for dxks. +
  14. +-------------------------------------+
  15. '''
  16.  
  17. with open( sys.argv[1] ) as fp:
  18. result = [re.match('\d{1,3}\.(.*)',i).group(1) if re.match('\d{1,i) else i.strip() for i in fp ]
  19. rlen = len(result)
  20.  
  21. ques_now_count = 0
  22. def givemeanswer( string,aflag ):
  23. global ques_now_count
  24. ques_now_count += 1
  25. if aflag:
  26. for j in xrange(rlen):
  27. if string in result[j]:
  28. print '%d.%s'%(ques_now_count,string)
  29. print '%s\n%s\n\033[37;91m%s\033[0m'%(result[j+1],result[j+2],result[j+3])
  30. return
  31. else:
  32. for i in result:
  33. if string in i:
  34. print '%d.%s\033[37;91m%s\033[0m'%(ques_now_count,i[:-4],i[-4:])
  35. return
  36. print 'Not Found:',ques_now_count,'.',string
  37.  
  38. def main():
  39. print logo
  40. with open( sys.argv[2] ) as fp:
  41. result = [i for i in re.findall( '\d{1,3}\.(.*?。)',fp.read() )]
  42. if 80 == len(result):
  43. print '[+] Found question: 80,seems good.'
  44. else:
  45. print '[-] Something wrong... question number should be 80 but now is',len(result)
  46. print 'Input Enter to contiune...'
  47. raw_input()
  48. print '判断题:'
  49. for i in result[:20]:
  50. givemeanswer(i,0)#i[5:-8]
  51. print '选择题:'
  52. for i in result[20:]:#i[5:-8]
  53. givemeanswer(i,1)
  54.  
  55.  
  56. if __name__ == '__main__':
  57. main()


自己对18行的这句

  1. result = [re.match('\d{1,i) else i.strip() for i in fp ]

觉得不错,挺pythonic。


运行:

python '/root/Desktop/党校考试/dxks_extract.py' '/root/Desktop/党校考试/dxks答案.txt' '/root/Desktop/党校考试/CakePHP the rapid development PHP framework Exams.html'

结果:

将选项填完。

结束后剩余9分钟。

得了满分。


结束了。



猜你在找的正则表达式相关文章