标签:
博客主页:http://blog.csdn.net/minna_d
起因:
我们经常会有驼峰字符串与下划线字符串相互转化的需求, 而且这个还不好之间用正则替换。
比如:db 表中命名风格通常为下划线风格, web应用pojo中通常有时驼峰风格。 如果字段太多,总觉得很麻烦
实现:
cm2us.py:
#!/bin/python import re import sys def camelToUnderlines(x): return re.sub('_([a-z])', lambda match: match.group(1).upper(), x) def underlinesToCamel(x): return re.sub('([a-zA-Z])([A-Z])', lambda match: match.group(1).lower() + "_" + match.group(2).lower(), x) def transStr(file_path, cmToUs_or_usToCm): f = open(file_path, 'r') if cmToUs_or_usToCm == 'cmToUs': for line in f.readlines(): print camelToUnderlines(line.strip()) elif cmToUs_or_usToCm == 'usToCm': for line in f.readlines(): print underlinesToCamel(line.strip()) f.close() if __name__ == '__main__': style = 'usToCm' if sys.argv[2]=="0" else 'cmToUs' transStr(sys.argv[1], style)
#!/bin/bash case $1 in /*) file_origin=$1 file_bak=`echo $1 | sed 's/^\/.*\/\(.*\)/\/tmp\/\1/g' `;; *) file_origin=`pwd`"/"$1 file_bak="/tmp/$1";; esac read -p "please input a number , 0 represent camelToUnderline, else represent underlineToCamel :" nu echo $file_origin echo $file_bak echo $nu cp $file_origin /tmp/ python /shell/python/cm2us.py $file_bak $nu > $file_origin
使用方式:示例
[root@jjy ~/q/data/tmp_data]# cm2us.sh date
please input a number , 0 represent camelToUnderline, else represent underlineToCamel :1
[root@jjy ~/q/data/tmp_data]# cat date
private String id;
private String wrapperId;
private String cityCode;
private String clstdCheckedCnt;
private String clstdNeedcheckCnt;
private String notClstdCnt;
private String deleteCnt;
private String manualCheckCnt;
private String clstdCheckedOnCnt;
private String clstdCheckedDelCnt;
private String clstdCheckedCleanCnt;
private String abnormalNeedcheckCnt;
private String hasPriceNeedcheckCnt;
[root@jjy ~/q/data/tmp_data]# cm2us.sh date
please input a number , 0 represent camelToUnderline, else represent underlineToCamel :0
[root@jjy ~/q/data/tmp_data]# cat date
private String id;
private String wrapper_id;
private String city_code;
private String clstd_checked_cnt;
private String clstd_needcheck_cnt;
private String not_clstd_cnt;
private String delete_cnt;
private String manual_check_cnt;
private String clstd_checked_on_cnt;
private String clstd_checked_del_cnt;
private String clstd_checked_clean_cnt;
private String abnormal_needcheck_cnt;
private String has_price_needcheck_cnt;
[root@jjy ~/q/data/tmp_data]# cm2us.sh date
please input a number , 0 represent camelToUnderline, else represent underlineToCamel :1
[root@jjy ~/q/data/tmp_data]# cat date
private String id;
private String wrapperId;
private String cityCode;
private String clstdCheckedCnt;
private String clstdNeedcheckCnt;
private String notClstdCnt;
private String deleteCnt;
private String manualCheckCnt;
private String clstdCheckedOnCnt;
private String clstdCheckedDelCnt;
private String clstdCheckedCleanCnt;
private String abnormalNeedcheckCnt;
private String hasPriceNeedcheckCnt;
标签:
原文地址:http://blog.csdn.net/minna_d/article/details/42490477