1

这很好:

import string
string.capwords("proper name")

Out: 'Proper Name'

这不太好:

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

Out: 'I.r.s'

是否没有字符串方法来做 capwords 以适应首字母缩略词?

4

4 回答 4

8

这可能有效:

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."
于 2009-01-26T08:08:40.417 回答
2

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

于 2009-01-26T07:36:00.857 回答
1

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

于 2009-01-26T07:37:13.943 回答
-1

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

于 2009-01-26T08:38:23.477 回答