是否有一个字符串方法来在python中大写首字母缩略词?

时间:2009-01-26 07:33:45

标签: python string acronym capitalize

这很好:

  
    
      

导入字符串       string.capwords(“专有名称”)       '专有名字'

    
  

这不太好:

  
    
      

string.capwords( “I.R.S”)       'I.r.s'

    
  

是否没有字符串方法来执行capwords以便它可以容纳缩写词?

4 个答案:

答案 0 :(得分: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."

答案 1 :(得分:2)

不,标准库中没有这样的方法。

答案 2 :(得分:1)

即使有这样的功能,当被要求处理“IRS”时会怎么做?甚至美国国税局也称自己为“IRS”而没有任何点。

答案 3 :(得分:-1)

我刚刚使用了列表解析:[“。”。join([string.capwords(l)for entry in entry.split(“。”)])for original_list]

相关问题