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

How to separate a irregularly cased string to get the words? - Python

我有以下单词表。

因为我的话并不都是用大写字母分隔的。单词列表将包含诸如 'USA' 之类的单词,我不确定该怎么做。 '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']

单词能分开

你可以使用 re.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' ', word)
    return all_cap_re.sub(r' ', s1)


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

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

您可以使用正则表达式为不在单词开头的每个大写字母加上 space:

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

第一对括号中的位表示"not at the beginning of a word",第二对括号中的位表示"followed by an uppercase letter"。正则表达式在满足这两个条件的地方匹配空字符串,并用space替换空字符串,即在这些位置插入space。

可以使用正则表达式执行此操作,但使用小算法更容易理解(忽略像 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)

以下代码片段可根据需要分隔单词:

myList=[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'managerYearsEndYear', 'horseRidingDiscipline']

updatemyList = []


for word in myList:
    phrase = word[0]

    for letter in word[1:]:
        if letter.isupper():
           phrase += " "
        phrase += letter

    updatemyList.append(phrase)

print updatemyList

你能不能简单地检查一下单词中的所有字母是否都是大写字母,如果是,忽略它们,即将它们算作一个单词?

我过去使用过类似的代码,它看起来有点硬编码,但它工作正常(在我的例子中,我想捕获最多 4 个字母的缩写)

def CapsSumsAbbv():
for word in words:
        for i,l in enumerate(word):
            try:
                if word[i] == word[i].upper() and word[i+1] == word[i+1].upper() and word[i+2] == word[i+2].upper() and word[i+3] == word[i+3].upper():
                    try:
                        word = int(word)
                    except:
                        if word not in allcaps:
                            allcaps.append(word)
            except:
                pass

为了进一步扩展,如果您有诸如 u'USAMilitarySpending' 之类的条目,您可以调整上面的代码,这样如果一行中有两个以上的大写字母,但也有小写字母,则 space 添加在 lastlast-1 大写字母之间,因此它变成 u'USA Military Spending'