Advertisement
Guest User

Untitled

a guest
Oct 19th, 2014
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. def ProcessImports(fileAsString):
  2. """
  3. Checks if the file includes import statements and acts upon them
  4.  
  5. Parameters
  6. ----------------
  7. fileAsString : str
  8. The file displayed as a string for search&replace
  9. """
  10.  
  11. foundStatements = re.findall(r"%@import.*", fileAsString)
  12.  
  13. if len(foundStatements) == 0:
  14. print "no %@import hits"
  15. else:
  16. print foundStatements
  17.  
  18. textblocksToImport = []
  19. iterator = 0
  20. for x in foundStatements:
  21. #splits %@import, the file parameter and the regex statement into separate strings. Makes sure to remove parentheses.
  22. splittedStatement = re.split(r"\s", x, 2)
  23. splittedStatement[2] = splittedStatement[2][1:-1]
  24.  
  25. fileToImportFrom = open(splittedStatement[1], "r")
  26. fileToImportFromAsString = fileToImportFrom.read()
  27. fileToImportFrom.close()
  28.  
  29. textToImport = re.search(splittedStatement[2], fileToImportFromAsString)
  30. latexPreparedString = ""
  31. if textToImport:
  32. #TODO? handle multiple hits (group(x))? As-is you have to make sure your regex statement hits the intended code block and not multiple ones, or it will just replace with the first hit.
  33. latexPreparedString = r"\\begin{verbatim}"+"\n"+textToImport.group(0)+"\n"+r"\end{verbatim}"
  34.  
  35. print "regex statement: ", foundStatements[iterator]
  36. print "string to replace with: \n", latexPreparedString
  37. #print "string to search&replace in: \n", fileAsString
  38. print iterator
  39. processedString = re.sub(re.escape(foundStatements[iterator]), latexPreparedString, fileAsString)
  40. textblocksToImport.append(latexPreparedString)
  41. iterator=iterator+1
  42.  
  43. #below is alternative solution that is less effective than using re.escape. Keeping it in case it turns out it's needed again
  44. #processedString = fileAsString
  45. #iterator = 0
  46. #for x in foundStatements:
  47. #processedString = re.sub(r"%@import.*", textblocksToImport[iterator], processedString, 1)
  48. #iterator = iterator+1
  49. print processedString
  50. return processedString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement