/
snake_to_camel.py
executable file
·77 lines (64 loc) · 1.76 KB
/
snake_to_camel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import os
from tempfile import mkstemp
from shutil import move
def findSnake(content):
'''
>>> findSnake("_big fuck_zhu gaga_dku kk_z")
{'a_d': 'aD', 'k_z': 'kZ'}
'''
result = re.findall(r'[a-z]_[a-z]', content)
# 转换数据对的同时实现排重
trans_pair = dict((k, transToCamel(k)) for k in result)
return trans_pair
def transToCamel(txt):
'''
>>> transToCamel("a_b")
'aB'
'''
return txt[0]+txt[2].upper()
def replaceSnake(file_path):
'''进行替换
>>> replaceSnake('test.txt')
'''
# Create temp file
old_file = open(file_path)
print('替换: ' + file_path)
old_file.seek(0)
old_file = open(file_path)
fh, abs_path = mkstemp()
new_file = open(abs_path, 'w')
for line in old_file:
new_line = line
# 找到需要替换的字符并且循环
for k, v in findSnake(line).items():
new_line = new_line.replace(k, v)
new_file.write(new_line)
# close temp file
new_file.close()
os.close(fh)
old_file.close()
# Remove original file
os.remove(file_path)
# Move new file
move(abs_path, file_path)
file_paths = []
def getFilePath(root_path):
for lists in os.listdir(root_path):
if lists in ('.git', 'node_modules'):
continue
the_path = os.path.join(root_path, lists)
if os.path.isdir(the_path):
getFilePath(the_path)
else:
file_paths.append(the_path)
return file_paths
if __name__ == '__main__':
#import doctest
#doctest.testmod(verbose=False, optionflags=doctest.ELLIPSIS)
path = os.getcwd()
getFilePath(path)
for file_path in file_paths:
replaceSnake(file_path)