No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
Este repositorio está archivado. Puede ver los archivos y clonarlo, pero no puede subir cambios o reportar incidencias ni pedir Pull Requests.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Advanced Text Replacer module for a KaiSD Text Tools.
  5. (c) 2013 Ivan "Kai SD" Korystin
  6. License: GPLv3
  7. '''
  8. import re
  9. class ATR(object):
  10. '''
  11. Advanced Text Replacer - is a class, created to make multiple replacements
  12. in the content or names of text file.
  13. It can make plain replacements, or use ATG templates to do something more complex.
  14. '''
  15. def __init__(self, files):
  16. '''
  17. Constructor
  18. '''
  19. self.files = files
  20. self.replacements = []
  21. def plain_replace(self, pattern, string, regexp=False):
  22. '''
  23. Replaces the given pattern with string in files.
  24. '''
  25. if regexp:
  26. pattern = re.compile(pattern)
  27. self.replacements.append((pattern, string))
  28. def templated_replace(self, pattern, template, data, keyFormat='filename', regexp=False):
  29. '''
  30. Replaces the given pattern with data formated by template.
  31. Valid values for keyFormat:
  32. filename - take data rows by filename(path ignored), key value of the data row should store the filename.
  33. fullname - as filename, but with path.
  34. index - take data rows in order, key value of the data row should store the index. Indexes starts with 0.
  35. If filename or index cannot be found in data keys, pattern will not be replaced.
  36. '''
  37. if regexp:
  38. pattern = re.compile(pattern)
  39. strings = template.process(data)
  40. self.replacements.append((pattern, strings, keyFormat))
  41. def write_in_place(self):
  42. '''
  43. Do replacement and save the files
  44. '''
  45. for f in self.files:
  46. out = u''
  47. with open(f, 'rb') as file:
  48. out = file.read()
  49. idx = 0
  50. for r in self.replacements:
  51. if type(r[0]) in (str, unicode):
  52. pattern = re.compile(re.escape(r[0]))
  53. string = r[1]
  54. elif type(r[0]) is dict and len(r) == 3:
  55. if r[2] == 'filename':
  56. fname = f.replace('\\', '/').split('/')[-1]
  57. string = f[1].get(fname, None)
  58. elif r[2] == 'fullname':
  59. string = f[1].get(f, None)
  60. elif r[2] == 'index':
  61. fname = f.replace('\\', '/').split('/')[-1]
  62. string = f[1].get(idx, None)
  63. else:
  64. raise BaseException('Unknown data key format.')
  65. elif hasattr(r[0], 'match'):
  66. pattern = r[0]
  67. string = r[1]
  68. else:
  69. raise BaseException('Unknown pattern type.')
  70. if string:
  71. out = re.sub(pattern, string, out)
  72. with open(f, 'wb') as outfile:
  73. outfile.write(out)
  74. def write_new_files(self, outfiles):
  75. '''
  76. Do replacement, but save to given files instead of the original ones.
  77. '''
  78. if not len(outfiles) == len(self.files):
  79. raise BaseException('Lists of original and new files has different length.')
  80. for f in self.files:
  81. out = u''
  82. with open(f, 'rb') as file:
  83. out = file.read()
  84. idx = 0
  85. for r in self.replacements:
  86. if type(r[0]) in (str, unicode):
  87. pattern = re.compile(re.escape(r[0]))
  88. string = r[1]
  89. elif type(r[0]) is dict and len(r) == 3:
  90. if r[2] == 'filename':
  91. fname = f.replace('\\', '/').split('/')[-1]
  92. string = f[1].get(fname, None)
  93. elif r[2] == 'fullname':
  94. string = f[1].get(f, None)
  95. elif r[2] == 'index':
  96. fname = f.replace('\\', '/').split('/')[-1]
  97. string = f[1].get(idx, None)
  98. else:
  99. raise BaseException('Unknown data key format.')
  100. elif hasattr(r[0], 'match'):
  101. pattern = r[0]
  102. string = r[1]
  103. else:
  104. raise BaseException('Unknown pattern type.')
  105. if string:
  106. out = re.sub(pattern, string, out)
  107. with open(outfiles[self.files.index(f)], 'wb') as outfile:
  108. outfile.write(out)
  109. def replace_in_names(self):
  110. '''
  111. Do replacement, but in file names instead of file content. Returns the list of new file names,
  112. you can use it with writeNewFiles() method.
  113. '''
  114. out = []
  115. for f in self.files:
  116. new = f
  117. idx = 0
  118. for r in self.replacements:
  119. if type(r[0]) in (str, unicode):
  120. pattern = re.compile(re.escape(r[0]))
  121. string = r[1]
  122. elif type(r[0]) is dict and len(r) == 3:
  123. if r[2] == 'filename':
  124. fname = f.replace('\\', '/').split('/')[-1]
  125. string = f[1].get(fname, None)
  126. elif r[2] == 'fullname':
  127. string = f[1].get(f, None)
  128. elif r[2] == 'index':
  129. fname = f.replace('\\', '/').split('/')[-1]
  130. string = f[1].get(idx, None)
  131. else:
  132. raise BaseException('Unknown data key format.')
  133. elif hasattr(r[0], 'match'):
  134. pattern = r[0]
  135. string = r[1]
  136. else:
  137. raise BaseException('Unknown pattern type.')
  138. if string:
  139. new = re.sub(pattern, string, new)
  140. out.append(new)
  141. return out
  142. def clear_replacements(self):
  143. '''
  144. Removes all replacements.
  145. '''
  146. self.replacements = []
  147. def log(self, string):
  148. '''
  149. Print information
  150. '''
  151. pass