Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def ProcessImports(fileAsString):
- """
- Checks if the file includes import statements and acts upon them
- Parameters
- ----------------
- fileAsString : str
- The file displayed as a string for search&replace
- """
- foundStatements = re.findall(r"%@import.*", fileAsString)
- if len(foundStatements) == 0:
- print "no %@import hits"
- else:
- print foundStatements
- textblocksToImport = []
- iterator = 0
- for x in foundStatements:
- #splits %@import, the file parameter and the regex statement into separate strings. Makes sure to remove parentheses.
- splittedStatement = re.split(r"\s", x, 2)
- splittedStatement[2] = splittedStatement[2][1:-1]
- fileToImportFrom = open(splittedStatement[1], "r")
- fileToImportFromAsString = fileToImportFrom.read()
- fileToImportFrom.close()
- textToImport = re.search(splittedStatement[2], fileToImportFromAsString)
- latexPreparedString = ""
- if textToImport:
- #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.
- latexPreparedString = r"\\begin{verbatim}"+"\n"+textToImport.group(0)+"\n"+r"\end{verbatim}"
- print "regex statement: ", foundStatements[iterator]
- print "string to replace with: \n", latexPreparedString
- #print "string to search&replace in: \n", fileAsString
- print iterator
- processedString = re.sub(re.escape(foundStatements[iterator]), latexPreparedString, fileAsString)
- textblocksToImport.append(latexPreparedString)
- iterator=iterator+1
- #below is alternative solution that is less effective than using re.escape. Keeping it in case it turns out it's needed again
- #processedString = fileAsString
- #iterator = 0
- #for x in foundStatements:
- #processedString = re.sub(r"%@import.*", textblocksToImport[iterator], processedString, 1)
- #iterator = iterator+1
- print processedString
- return processedString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement