avatar


将连续的英文字符串转成小驼峰(Python)

下划线拼接

如果是用下划线_来拼接的话,那么非常简单。
例如user_nameprice_earnings_ratiohtml_a_content,我们通过下划线_分割,然后从第二个项开始,首字母大写。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
l = ['user_name', 'price_earnings_ratio', 'html_a_content']

for src in l:
sl = src.split('_')
des = ''
index = 0
for sl_item in sl:
if index == 0 or len(sl_item) == 1:
des = des + sl_item
else:
des = des + sl_item.title()
index = index + 1

print(src)
print(des)
print()

运行结果:

1
2
3
4
5
6
7
8
user_name
userName

price_earnings_ratio
priceEarningsRatio

html_a_content
htmlaContent

解释说明:

  • .title():首字母大写。

连续的

但,如果是连续的呢?
例如,usernamepriceearningsratiohtmlacontent
这个时候,就需要借助第三方的包wordninja

分词

分词的方法为:wordninja.split(被分词的对象)

示例代码:

1
2
3
import wordninja
s = 'ilovechina'
print(wordninja.split(s))

运行结果:

1
['i', 'love', 'china']

小驼峰

将连续的英文字符串转成小驼峰(Python),示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import wordninja

l = ['username', 'priceearningsratio', 'htmlacontent']

for src in l:
sl = wordninja.split(src)
des = ''
index = 0
for sl_item in sl:
if index == 0 or len(sl_item) == 1:
des = des + sl_item
else:
des = des + sl_item.title()

index = index + 1

print(src)
print(des)
print()

运行结果:

1
2
3
4
5
6
7
8
username
username

priceearningsratio
priceEarningsRatio

htmlacontent
htmlaContent

修改词库

我们看到username,结果依旧是username
wordninja是基于维基百科语料的频率来进行分词的,如果想对特有名词进行正确分割,需要修改词库,将特有名词加入词库中。
我们可以通过如下的地址 https://github.com/keredson/wordninja/ ,找到词库,在wordninja目录下,wordninja_words.txt.gz
解压后,我们添加单词user,并删去username,然后重新打成.gz

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import wordninja

l = ['username', 'priceearningsratio', 'htmlacontent']

for src in l:
myw = wordninja.LanguageModel('wordninja_words.txt.gz')
sl = myw.split(src)
des = ''
index = 0
for sl_item in sl:
if index == 0 or len(sl_item) == 1:
des = des + sl_item
else:
des = des + sl_item.title()

index = index + 1

print(src)
print(des)
print()

运行结果:

1
2
3
4
5
6
7
8
username
userName

priceearningsratio
priceEarningsRatio

htmlacontent
htmlaContent

关于打成.gz包:

实际上,这些字段,都是数据库中的字段,这个小技巧的背景也就是数据库中字段的映射。
所以,接下来还可以做很多事情,包括用Python直接生成Java语言的代码。

文章作者: Kaka Wan Yifan
文章链接: https://kakawanyifan.com/19904
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kaka Wan Yifan

留言板