2009-01-26 30 views
0

這是好事:有沒有一種字符串方法來大寫python中的首字母縮略詞?

進口字符串 string.capwords( 「專名」) '正確的名稱'

這也不是那麼好:

string.capwords( 「I.R.S」) 'I.r.s'

有沒有字符串的方法做capwords,使其可容納的縮寫?

+0

IRS是縮寫,而不是縮寫。首字母縮略詞(一般)是可以發音的;傳統上沒有標點符號。 – 2009-01-26 11:23:31

+0

我相信你的意思是初始主義,先生。縮寫是不,不會,不會。首字母縮寫詞就像VISA。初始主義是你不能發音的東西。 但我們離題了。 – mlissner 2010-05-04 21:21:44

回答

5

這可能會實現:

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." 
2

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

1

即使有這樣的功能,當它被要求處理「IRS」時它會做什麼?即使是國稅局自稱「國稅局」沒有點。

-1

我只是用一個列表理解: 「」[加入([string.capwords(L)對於L in entry.split(「。」)])用於在original_list中輸入]

相關問題