本文介绍了Python:如何使用下划线将混合大小写重命名为小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一些我的第一个重要的Python脚本。我刚刚读完PEP 8,我了解到lower_case_with_underscores是实例变量名的首选。我一直在使用mixedCase作为变量名,我希望我的代码可以通过将那些更改为lower_case_with_underscores来制作更多Pythonic,如果这就是我们在这里做的事情。



解决方案

我能够用GNU sed完成我想要的东西:

  sed -i -e:loop -re's /(^ | [^ A-Za-z _])([a -z0-9 _] +)([AZ])([A-Za-z0-9 _] *)'\ 
'([^ A-Za-z0-9_] | $)/ \\\ \2_\\\\\\ /'-e't循环'myFile.py

它找到mixedCase的每个实例 - 但不是CapitalWords,所以类名保持不变 - 并用lower_case_with_underscores替换它;例如myVariable变成了my_variable,但是MyClass仍然是MyClass。



(在一个不相关的注释中,既然我已经完成了它,我想我更喜欢使用mixedCase而不是lower_case_with_underscores。在我的代码中出现如此多的下划线是很奇怪的。但是我会用Python方式做事,看看我是否习惯了它,特别是如果我打算让我的代码被其他人看到或合作;或者我可能我会按照自己喜欢的方式进行操作,如果我打算将代码公开,我现在可以通过简单的方式将其转换为PEP 8方式。)


I've written a fair bit of my first significant Python script. I just finished reading PEP 8, and I learned that lower_case_with_underscores is preferred for instance variable names. I've been using mixedCase for variable names throughout, and I'd like my code to be make more Pythonic by changing those to lower_case_with_underscores if that's how we do things around here.

I could probably write some script that searches for mixedCase and tries to smartly replace it, but before I potentially reinvent the wheel, my question is whether a solution for that already exists, either within a Python-savvy editor or as a standalone application; or whether there's another approach that would accomplish the task of converting all mixedCase variable names to lower_case_with_underscores. I have searched a fair bit for a solution but didn't turn up anything. Any technique that specifically would yield this result would be appreciated.

解决方案

I was able to accomplish what I wanted using GNU sed:

sed -i -e :loop -re 's/(^|[^A-Za-z_])([a-z0-9_]+)([A-Z])([A-Za-z0-9_]*)'\
'([^A-Za-z0-9_]|$)/\1\2_\l\3\4\5/' -e 't loop' myFile.py

It finds every instance of mixedCase -- but not CapitalWords, so class names are left intact -- and replaces it with lower_case_with_underscores; e.g. myVariable becomes my_variable, but MyClass remains MyClass.

(On an unrelated note, now that I've done it, I think I prefer the appearance of mixedCase over lower_case_with_underscores. The appearance of so many underscores all over my code is weird. But I'll do things the Python Way and see if I get used to it, particularly if I intend for my code to be seen or worked with by others; or maybe I'll do it the way I like and I've now got a simple way of converting it to the PEP 8 way if I intend to make the code public.)

这篇关于Python:如何使用下划线将混合大小写重命名为小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:19
查看更多