如何将不规则大小写的字符串分离以获取单词? - Python

2024-06-12 00:43:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的单词表。你知道吗

因为我的话不是全部用大写字母分隔的。词表上会有‘USA’之类的词,我不知道该怎么做“美国”应该是一个词。不能分开。你知道吗

myList=[u'USA',u'Chancellor', u'currentRank', u'geolocDepartment', u'populationUrban', u'apparentMagnitude', u'Train', u'artery',
       u'education', u'rightChild', u'fuel', u'Synagogue', u'Abbey', u'ResearchProject', u'languageFamily', u'building',
       u'SnookerPlayer', u'productionCompany', u'sibling', u'oclc', u'notableStudent', u'totalCargo', u'Ambassador', u'copilote',
       u'codeBook', u'VoiceActor', u'NuclearPowerStation', u'ChessPlayer', u'runwayLength', u'horseRidingDiscipline']

如何编辑列表中的元素。
我想更改列表中的元素,如下所示:

 updatemyList=[u'USA',u'Chancellor', u'current Rank', u'geoloc Department', u'population Urban', u'apparent Magnitude', u'Train', u'artery',
           u'education', u'right Child', u'fuel', u'Synagogue', u'Abbey', u'Research Project', u'language Family', u'building',
           u'Snooker Player', u'production Company', u'sibling', u'oclc', u'notable Student', u'total Cargo', u'Ambassador', u'copilote',
           u'code Book', u'Voice Actor', u'Nuclear Power Station', u'Chess Player', u'runway Length',  u'horse Riding Discipline']

这个词是可以分开的


Tags: 元素列表trainbuildingeducationfuelusasibling
3条回答

可以使用regex来实现这一点,但是使用一个小的算法更容易理解(忽略诸如NLTK之类的缩写)

def split_camel_case(string):
    new_words = []
    current_word = ""
    for char in string:
        if char.isupper() and current_word:
            new_words.append(current_word)
            current_word = ""
        current_word += char
    return " ".join(new_words + [current_word])


old_words = ["HelloWorld", "MontyPython"]
new_words = [split_camel_case(string) for string in old_words]
print(new_words)

你可以用回复sub你知道吗

import re 

first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')


def convert(word):
    s1 = first_cap_re.sub(r'\1 \2', word)
    return all_cap_re.sub(r'\1 \2', s1)


updated_words = [convert(word) for word in myList]

改编自:Elegant Python function to convert CamelCase to snake_case?

可以使用正则表达式在每个不在单词开头的大写字母前面加空格:

re.sub(r"(?!\b)(?=[A-Z])", " ", your_string)

第一对括号中的位表示“不在单词的开头”,第二对括号中的位表示“后跟大写字母”。正则表达式在这两个条件所在的位置匹配空字符串,并用空格替换空字符串,即在这些位置插入空格。你知道吗

相关问题 更多 >