簡體   English   中英

是否有字符串方法來大寫python中的首字母縮略詞?

[英]is there a string method to capitalize acronyms in python?

這很好:

import string
string.capwords("proper name")

Out: 'Proper Name'

這不太好:

string.capwords("I.R.S")

Out: 'I.r.s'

有沒有字符串方法來做大寫字母,以便它容納首字母縮略詞?

這可能有效:

import re

def _callback(match):
    """ This is a simple callback function for the regular expression which is 
        in charge of doing the actual capitalization. It is designed to only 
        capitalize words which aren't fully uppercased (like acronyms).
    """
    word = match.group(0)
    if word == word.upper():
        return word
    else:
        return word.capitalize()

def capwords(data):
    """ This function converts `data` into a capitalized version of itself. This 
        function accomidates acronyms.
    """
    return re.sub("[\w\'\-\_]+", _callback, data)

這是一個測試:

print capwords("This is an IRS test.")    # Produces: "This Is An IRS Test."
print capwords("This is an I.R.S. test.") # Produces: "This Is An I.R.S. Test."

不,標准庫中沒有這樣的方法。

即使有這樣的功能,當被要求處理“IRS”時它會做什么? 甚至國稅局也稱自己為“國稅局”,沒有點。

我只是使用了列表理解:[ ".".join( [ string.capwords(l) for l in entry.split(".") ] ) for entry in original_list ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM