Table of Contents
分割单词
分割成全小写单词
分割成全大写单词
分割成首大写、其余小写单词
转中划线命名法
转小蛇式命名法
转大蛇式命名法
转小驼峰命名法
转大驼峰命名法
Home Backend Development Python Tutorial How to split words and convert naming in Python

How to split words and convert naming in Python

May 13, 2023 pm 12:31 PM
python

分割单词

将一个标识符分割成若干单词存进列表,便于后续命名法的转换

先引入正则表达式包

import re
Copy after login

至于如何分割单词看个人喜好,如以常见分隔符 “ ”、“_”、“-”、“/”、“\” 去分割

re.split('[ _\-/\\\\]+', name)
Copy after login

还可以范围再广一点,拿除了数字和字母以外的所有字符去分割

re.split('[^0-9a-zA-Z]', name)
Copy after login

那对于字母内部怎么分割呢?

综合考虑驼峰命名法、连续大写的缩写单词等,笔者根据经验一般会采用这种策略,连续比较三个字符,满足以下条件之一就分割:“小|大无”、“有|大小”、“小|大有”

  • 是尾字符,是大写,倒数第二个字符是小写,在尾字符前分割,比如 'getA' 分割成 ['get','A']

  • 是非首位的中间字符,是大写,前后至少有一个是小写,在该字符前分割,比如 'getJSONString' 分割成 ['get','JSON','String']

对于字母和数字结合的标识符,就比较难处理了

因为有的数字可以作为单词开头(比如 '3D'),有的又可以作为结尾(比如 'HTML5'),还有的字母数字交错(比如 'm3u8'),暂未想到通用的分割的好办法,根据个人需求实现就行了

综合以上几者的分割函数如下

def to_words(name):
    words = []                  # 用于存储单词的列表
    word = ''                   # 用于存储正在构建的单词

    if(len(name) <= 1):
        words.append(name)
        return words

    # 按照常见分隔符进行分割
    # name_parts = re.split(&#39;[ _\-/\\\\]+&#39;, name)
    # 按照非数字字母字符进行分割
    name_parts = re.split(&#39;[^0-9a-zA-Z]&#39;, name)
    for part in name_parts:
        part_len = len(part)        # 字符串的长度
        word = ''
        # 如果子串为空,继续循环
        if not part:
            continue   
        for index, char in enumerate(part):
            # “小|大无”
            if(index == part_len - 1):
                if(char.isupper() and part[index-1].islower()):
                    if(word): words.append(word)
                    words.append(char)
                    word = ''
                    continue

            # “有|大小”或“小|大有”
            elif(index != 0 and char.isupper()):
                if((part[index-1].islower() and part[index+1].isalpha()) or (part[index-1].isalpha() and part[index+1].islower())):
                    if(word): words.append(word)
                    word = ''
            word += char
        if(len(word) > 0): words.append(word)
    # 去除空单词
    return [word for word in words if word != '']
Copy after login

测试用例如下

print(to_words(&#39;IDCard&#39;)) # [&#39;ID&#39;, &#39;Card&#39;]
print(to_words(&#39;getJSONObject&#39;)) # [&#39;get&#39;, &#39;JSON&#39;, &#39;Object&#39;]
print(to_words(&#39;aaa@bbb.com&#39;)) # [&#39;aaa&#39;, &#39;bbb&#39;, &#39;com&#39;]
print(to_words(&#39;D://documents/data.txt&#39;)) # [&#39;D&#39;, &#39;documents&#39;, &#39;data&#39;, &#39;txt&#39;]
Copy after login

分割成全小写单词

def to_lower_words(name):
    words = to_words(name)
    return [word.lower() for word in words]
Copy after login

分割成全大写单词

def to_upper_words(name):
    words = to_words(name)
    return [word.upper() for word in words]
Copy after login

分割成首大写、其余小写单词

def to_capital_words(name):
    words = to_words(name)
    return [word.capitalize() for word in words]
Copy after login

转中划线命名法

中划线命名法,也叫烤肉串命名法(kebab case),如 'kebab-case'

  • 字母全小写

  • 连字符连接

def to_kebab_case(name):
    words = to_lower_words(name)
    to_kebab_case = &#39;-&#39;.join(words)
    return to_kebab_case
Copy after login

转小蛇式命名法

小蛇式命名法,其实就是小写下划线命名法,也叫蛇式命名法(snake case),如 'snake_case'

  • 字母全小写

  • 下划线连接

def to_snake_case(name):
    words = to_lower_words(name)
    snake_case_name = &#39;_&#39;.join(words)
    return snake_case_name
Copy after login

转大蛇式命名法

大蛇式命名法,其实就是大写下划线命名法,也叫宏命名法(macro case),如 'MACRO_CASE'

  • 字母全大写

  • 下划线连接

def to_macro_case(name):
    words = to_upper_words(name)
    snake_case_name = &#39;_&#39;.join(words)
    return snake_case_name
Copy after login

转小驼峰命名法

小驼峰命名法,也叫驼峰命名法(camel case) ,如 'camelCase'

  • 首单词首字母小写,后每个单词首字母大写

  • 不使用连接符

def to_camel_case(name):
    words = to_words(name)
    camel_case_words = []
    for word in words:
        if len(word) <= 1:
            camel_case_words.append(word.upper())
        else:
            camel_case_words.append(word[0].upper() + word[1:])

    camel_case = &#39;&#39;.join(camel_case_words)
    if len(camel_case) <= 1:
        camel_case = camel_case.lower()
    else:
        camel_case = &#39;&#39;.join(camel_case[0].lower() + camel_case[1:])
    return camel_case
Copy after login

转大驼峰命名法

大驼峰命名法,也叫帕斯卡命名法(pascal case) ,如 'PascalCase'

  • 每个单词首字母大写

  • 不使用连接符

def to_pascal_case(name):
    words = to_words(name)
    pascal_case_words = []
    for word in words:
        if len(word) <= 1:
            pascal_case_words.append(word.upper())
        else:
            pascal_case_words.append(word[0].upper() + word[1:])
    pascal_case = &#39;&#39;.join(pascal_case_words)
    return pascal_case
Copy after login

The above is the detailed content of How to split words and convert naming in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles