is there a string method to capitalize acronyms in python?

半腔热情 提交于 2019-12-11 16:12:56

问题


This is good:

import string string.capwords("proper name") 'Proper Name'

This is not so good:

string.capwords("I.R.S") 'I.r.s'

Is there no string method to do capwords so that it accomodates acronyms?


回答1:


This might work:

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)

Here is a test:

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:


No, there is no such method in the standard library.




回答3:


Even if there were such a function, what would it do when asked to process "IRS"? Even the IRS call themselves "IRS" with no dots.




回答4:


I just used a list comprehension: [ ".".join( [ string.capwords(l) for l in entry.split(".") ] ) for entry in original_list ]



来源:https://stackoverflow.com/questions/479043/is-there-a-string-method-to-capitalize-acronyms-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!