驼峰与小写互转
舟率率 10/7/2023 python
# 驼峰转小写
#!/usr/bin/python
# -*- encoding: utf-8 -*-
"""
@Author: apophis
@File: camel_to_lower_underscore.py
@Time: 2023/9/27 8:33
@Description: 工程描述
"""
import re
def run(name):
"""
将驼峰命名转为小写字母、下划线和数字组成的名称
:param name:
:return:
"""
# 将驼峰命名转为小写字母、下划线和数字组成的名称
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) # 将大写字母前面加上下划线
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name) # 将大写字母转为小写,并在前面加上下划线
name = re.sub('(^[0-9]+)(.+)', r'\2_\1', name) # 将字母和数字位置互换,并在中间加上下划线 仅针对以数字开头的情况
name = re.sub('__+', '_', name) # 将连续的下划线替换为单个下划线
name = name.strip("_") # 去除开头和结尾的下划线
name = name.lower() # 将名称转为小写
name = name.replace(".", "")
name = "_".join([wd_map.get(_, _) for _ in name.split("_")])
return name
def read_txt(file):
with open(file, "r", encoding="utf8") as f:
return [line.strip("\n") for line in f.readlines()]
def test():
print(run("camelCaseName")) # 输出:camel_case_name
print(run("anotherExample123")) # 输出:another_example123
print(run("HTTPRequest")) # 输出:http_request
print(run("someURLValue")) # 输出:some_url_value
print(run("HTMLParser")) # 输出:html_parser
print(run("URLValue")) # 输出:url_value
print(run("44lan"))
print(run("GGLanMdw"))
print(run("GGLanMdw_GqweGqs"))
print(run("GGLanMdw_GGqweGqs"))
print(run("GGLanMdw_qqweGqs"))
print(run("aaaGGLanMdw_qqweGqs"))
print(run("aaaGGLan123Mdw_qqweGqs"))
print(run("AaBbCcDd"))
if __name__ == '__main__':
for name in read_txt("E:/测试用/1.txt"):
print(run(name))
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
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
# 小写转驼峰
#!/usr/bin/python
# -*- encoding: utf-8 -*-
"""
@Author: apophis
@File: lower_underscore_to_camel.py
@Time: 2023/9/27 9:56
@Description: 工程描述
"""
import re
def run(name):
"""
将小写字母、下划线和数字组成的名称转为驼峰命名
:param name:
:return:
"""
name = re.sub('__+', '_', name) # 将连续的下划线替换为单个下划线
name = name.strip("_")
# 将字母和数字位置互换
arr = [re.sub('(^[0-9]+)(.+)', r'\2\1', _) for _ in name.split("_")]
# capitalize 将开头的首字母转换成大写
# 整个字符串的首位不需要转换成大写
name = "".join([arr[_].lower() if _ == 0 else arr[_].capitalize() for _ in range(len(arr))])
return name
def read_txt(file):
with open(file, "r", encoding="utf8") as f:
return [line.strip("\n") for line in f.readlines()]
def test():
print(run("1a_2b_3c"))
print(run("aa_bb_cc"))
print(run("1a_BBc_3c"))
print(run("_1a_BBc_3c_"))
if __name__ == '__main__':
for name in read_txt("E:/测试用/1.txt"):
print(run(name))
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
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