Guest User

Untitled

a guest
Jun 24th, 2017
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. import re
  2. import sys
  3.  
  4. #variables to set
  5. relfirst = "relfirst"
  6. relsecond = "relsecond"
  7.  
  8. #read file name from command line
  9. if len(sys.argv) == 1:
  10.     print("This script takes a filename as a parameter")
  11.     sys.exit()
  12. elif len(sys.argv) == 2:
  13.     origFileName = sys.argv[1]
  14.     newFileName = "new_"+sys.argv[1]
  15. else:
  16.     origFileName = sys.argv[1]
  17.     newFileName = sys.argv[2]
  18.  
  19.  
  20. #Reads the old file in, probably slow if your file is very big, but you didn't specify that
  21. textfile = open(origFileName, 'r')
  22. filetext = textfile.read()
  23. textfile.close()
  24.  
  25. #This is called a regular expression, its a fancy way to find something, look it up online
  26. pattern = re.compile("(?<=<"+relfirst+">).*?(?=</"+relfirst+">)|(?<=<"+relsecond+">).*?(?=</"+relsecond+">)",re.DOTALL)
  27. matches = pattern.findall(filetext)
  28.  
  29. if len(matches) == 0:
  30.     print("No match found")
  31. else:
  32.     #open the new file where we write the result
  33.     newfile = open(newFileName,'w')
  34.    
  35.     #write the start of the thing, you might want to tweak this
  36.     newfile.write("""<?xml version="1.0"?>
  37. <fixed>
  38.     <useless>0</useless>""")
  39.     i=0
  40.     #Run through all the items in the file
  41.     while i < len(matches):
  42.         firstStringYouWanted = matches[i];
  43.         secondStringYouWanted = matches[i+1];
  44.  
  45.         #Write each item into new file, you might want to tweak the stuff below
  46.         newfile.write("""
  47.     <fixeditem>
  48.         <type>s</type>
  49.         <first>"""+firstStringYouWanted+"""</first>
  50.         <second>"""+secondStringYouWanted+"""</second>
  51.     </fixeditem>""")
  52.         i=i+2
  53.     #write the last part, you might want to tweak this
  54.     newfile.write("\n</fixed>")
  55.     newfile.close()
  56.     print("Sucessfully searched/replaced everything")
Add Comment
Please, Sign In to add comment