Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
Це архівний репозитарій. Ви можете переглядати і клонувати файли, але не можете робити пуш або відкривати питання/запити.

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