Advertisement
cmiN

qrand

Apr 14th, 2014
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.34 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3.  
  4. """qrand: creeaza variante aleatoare de teste grila
  5.  
  6. Fisierul de intrare trebuie sa respecte un format destul de simplu:
  7.    - fiecare intrebare trebuie sa contina cel putin un raspuns
  8.    - intrebarile sunt prefixate de un numar, apoi punct si unul sau mai multe spatii
  9.    - raspunsurile sunt prefixate de o litera, apoi paranteza rotunda inchisa
  10.      si unul sau mai multe spatii
  11.  
  12. Grupurile de intrebari + raspunsuri nu trebuiesc delimitate de anumite
  13. caractere speciale, iar spatiile dintre raspunsuri sau intrebari nu sunt luate in calcul.
  14. Pentru siguranta, se recomanda ca atat intrebarile cat si raspunsurile aflate pe
  15. multiple linii sa fie indentate pentru a nu face confuzie.
  16. """
  17.  
  18.  
  19. import re
  20. import sys
  21. import random
  22. import argparse
  23.  
  24.  
  25. if "linux" in sys.platform:
  26.     EOL = "\n"
  27. else:
  28.     EOL = "\r\n"
  29.  
  30. SAMPLES = 1
  31. SEPARATOR = "{}\n".format("*" * 10)
  32.  
  33.  
  34. class QShuffle(object):
  35.  
  36.     """Q&A randomizer."""
  37.  
  38.     def __init__(self, fin, fout=sys.stdout,
  39.                  samples=SAMPLES, separator=SEPARATOR):
  40.         # read data and close the input buffer
  41.         self.data = fin.read()
  42.         fin.close()
  43.         # save output options
  44.         self.fout = fout
  45.         self.samples = samples
  46.         self.separator = separator
  47.         # randomized samples
  48.         self.pages = list()
  49.         # regexps
  50.         self.qregex = re.compile(r"[0-9]+(?=\.\s+)")
  51.         self.aregex = re.compile(r"[a-z](?=\)\s+)", re.IGNORECASE)
  52.  
  53.     def _shuffle(self):
  54.         # chunked question-answers groups
  55.         bits = list()
  56.         # question and answer parts
  57.         qpart, apart = list(), list()
  58.         crs = qpart    # cursor
  59.         # split data
  60.         addans = lambda: bits[-1][1].append(EOL.join(crs).strip())
  61.         for line in self.data.split(EOL):
  62.             if crs is qpart and self.aregex.match(line):
  63.                 bits.append([EOL.join(crs).strip(), list()])
  64.                 crs = apart
  65.             elif crs is apart and self.aregex.match(line):
  66.                 addans()
  67.                 crs = apart = list()
  68.             elif crs is apart and self.qregex.match(line):
  69.                 addans()
  70.                 qpart, apart = list(), list()
  71.                 crs = qpart
  72.             crs.append(line)
  73.         addans()
  74.         # randomize it
  75.         random.shuffle(bits)
  76.         for group in bits:
  77.             random.shuffle(group[1])
  78.         # update it
  79.         qind = 0
  80.         for group in bits:
  81.             group[0] = self.qregex.sub(str(qind + 1), group[0])
  82.             qind += 1
  83.             aind = 0
  84.             for pos in range(len(group[1])):
  85.                 char = chr(ord("a") + aind)
  86.                 aind += 1
  87.                 group[1][pos] = self.aregex.sub(char, group[1][pos])
  88.         # return new sample
  89.         return (EOL * 2).join([qstr + EOL + EOL.join(astrs)
  90.                                for qstr, astrs in bits]) + EOL
  91.  
  92.     def generate(self):
  93.         """Split data into question and answer parts,
  94.        then build new shuffled samples.
  95.        """
  96.         for _ in range(self.samples):
  97.             self.pages.append(self._shuffle())
  98.  
  99.     def save(self):
  100.         """Glue out together and write data to console/file."""
  101.         self.fout.write(self.separator.join(self.pages))
  102.         if isinstance(self.fout, file):
  103.             self.fout.close()
  104.  
  105.  
  106. def main():
  107.     # build parser
  108.     parser = argparse.ArgumentParser(description="Randomize questions.")
  109.  
  110.     # add options
  111.     parser.add_argument(
  112.         "-o", "--output",
  113.         type=argparse.FileType("w"),
  114.         default=sys.stdout,
  115.         help="output file"
  116.     )
  117.     parser.add_argument(
  118.         "-s", "--samples",
  119.         type=int, default=SAMPLES,
  120.         help="how many randomized copies to create"
  121.     )
  122.     parser.add_argument(
  123.         "-S", "--separator",
  124.         default=SEPARATOR,
  125.         help="separator between the copies"
  126.     )
  127.  
  128.     # add requiered positional arguments
  129.     parser.add_argument(
  130.         "input", metavar="INPUT",
  131.         type=argparse.FileType("r"),
  132.         help="input file"
  133.     )
  134.  
  135.     # parse and process them
  136.     args = parser.parse_args()
  137.     qshuffle = QShuffle(args.input, fout=args.output,
  138.                         samples=args.samples, separator=args.separator)
  139.     qshuffle.generate()
  140.     qshuffle.save()
  141.    
  142.  
  143. if __name__ == "__main__":
  144.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement