Advertisement
Guest User

Untitled

a guest
May 27th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.82 KB | None | 0 0
  1. #! /usr/bin/python
  2. """
  3. NoteReader
  4. """
  5. #CHANGELOG
  6. #
  7. # v0.07
  8. # * added getopt options parser
  9. #
  10. # v0.06
  11. # * added Trash section
  12. # * added Parser.save() function
  13. # * SORT flag in Parser
  14. # *
  15.  
  16. import sys
  17. import getopt
  18.  
  19. __VERSION__='0.07'
  20.  
  21. class Parser:
  22.     """Parser for files"""
  23.  
  24.     def __init__(self):
  25.         """init parser"""
  26.  
  27.         self._sections=[]
  28.         self.SORT=True
  29.  
  30.     def add_section(self,sectiondict):
  31.         """add section"""
  32.  
  33.         self._sections.append(sectiondict)
  34.  
  35.     def remove_section(self,sectiondict):
  36.         """remove section"""
  37.  
  38.         pass
  39.  
  40.     def get_sections(self):
  41.         """get all sections, unsorted"""
  42.  
  43.         return self._sections
  44.  
  45.     def get_section_names(self):
  46.         """get all section names"""
  47.        
  48.         result=[]
  49.         for sec in self._sections:
  50.             result.append(sec['name'])
  51.         if self.SORT:result.sort()
  52.         return result
  53.    
  54.     def get_section_tag(self,section):
  55.         """get tag of section
  56.        for #[/hello] its /hello and,
  57.        for #[/hello/world] its /hello/world
  58.        """
  59.  
  60.         tag=section['name'].lstrip('#[')
  61.         tag=tag.rstrip(']')
  62.         return tag
  63.    
  64.     def section_from_tag(self,tag):
  65.         """convert tag to section name"""
  66.        
  67.         return '#['+tag+']'
  68.  
  69.     def get_section_by_tag(self,tag):
  70.         """get section by given tag
  71.        tag should be like this /hello"""
  72.         section_name=self.section_from_tag(tag)
  73.         if section_name in self.get_section_names():
  74.             return self.get_section_by_name(section_name)
  75.  
  76.     def get_section_by_name(self,sectionname):
  77.         """get section by name"""
  78.  
  79.         for sec in self._sections:
  80.             if sec['name']==sectionname:
  81.                 return sec
  82.  
  83.     def save(self,filename):
  84.         """save all sections to the file"""
  85.  
  86.         try:
  87.             filew=open(filename,'w')
  88.         except:pass
  89.         else:
  90.             sections=self.get_section_names()
  91.             for sec in sections:
  92.                 nextsection=self.get_section_by_name(sec)
  93.                 filew.write(nextsection['name']+'\n')
  94.                 filew.write(nextsection['text'])
  95.             filew.close()
  96.  
  97. def Parse(pbuffer):
  98.     """parse the buffer"""
  99.  
  100.     current_section=None
  101.     trash_section={'name':'#[/trash]','text':''}
  102.     parser=Parser()
  103.    
  104.     #for each line in buffer
  105.     for nr,line in enumerate(pbuffer):
  106.         line=line.rstrip()
  107.         #found #[/text] --section
  108.         if line.startswith('#[/') and line.endswith(']'):
  109.             #store section
  110.             if current_section!=None:
  111.                 parser.add_section(current_section)
  112.             #create new section
  113.             current_section={'name':line,'text':''}
  114.  
  115.         #add rest text to current section
  116.         else:
  117.             #if we have current_section
  118.             if current_section!=None:
  119.                 #if this is not last line in buffer
  120.                 if nr!=len(pbuffer)-1:
  121.                     #not empty line
  122.                     if len(line)>0:
  123.                         current_section['text']+=line+'\n'
  124.                     #empty line
  125.                     else:
  126.                         current_section['text']+='\n'
  127.                 #if its last line in buffer
  128.                 else:
  129.                     current_section['text']+=line+'\n'
  130.             #if there no current_section then add it to trash
  131.             else:
  132.                 trash_section['text']+=line+'\n'
  133.     #add last section
  134.     if current_section!=None:
  135.         parser.add_section(current_section)
  136.  
  137.     if trash_section['text']!='':
  138.         parser.add_section(trash_section)
  139.  
  140.     return parser
  141.  
  142. def parse_args(opts,args):
  143.     """parse arguments passed to application"""
  144.  
  145.     for opt,arg in opts:
  146.         if opt=='-s' and len(args)>0:
  147.             buff=open(args[0]).readlines()
  148.             parsed=Parse(buff)
  149.             sections=parsed.get_section_names()
  150.             section=parsed.get_section_by_tag(arg)
  151.             if section:
  152.                 print section['text']
  153.         elif opt=='-h' or '--help':
  154.             print "Usage:"
  155.             print "NoteReader [Flags] filename"
  156.             print "Flags:"
  157.             print "-s <section> --show section e.g. -s /section"
  158.             print "-h --this help"
  159.     if not opts and len(args)>0:
  160.         buff=open(sys.argv[1]).readlines()
  161.         parsed=Parse(buff)
  162.         sections=parsed.get_section_names()
  163.         for sec in sections:
  164.             print sec
  165.  
  166. ############################
  167. if __name__=='__main__':
  168.     try:
  169.         opts,args=getopt.getopt(sys.argv[1:],'s:h',[])
  170.         if not opts and len(args)==0:
  171.             print "Invalid option try:NoteReader -h"
  172.     except getopt.GetoptError,Exception:
  173.         print "Invalid option try:NoteReader -h"
  174.     else:
  175.         parse_args(opts,args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement