Advertisement
Guest User

Untitled

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