【问题标题】:is there a string method to capitalize acronyms in python?有没有一种字符串方法可以在 python 中将首字母缩写词大写?
【发布时间】:2010-10-03 12:05:27
【问题描述】:

这很好:

import string
string.capwords("proper name")

Out: 'Proper Name'

这不太好:

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

Out: 'I.r.s'

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

【问题讨论】:

  • 我。 R.S. 是缩写,而不是首字母缩略词。首字母缩略词(通常)是可发音的;并且传统上没有标点符号。
  • 我相信您的意思是缩写,先生。缩写是诸如不要、不能、不会之类的东西。首字母缩略词类似于 VISA。首字母缩写词是你不能发音的东西。但我们离题了。

标签: python string acronym capitalize


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 但出于我的目的,使用句点/点是一种表示我希望每个字母都大写的方式。
    【解决方案3】:

    这可能有效:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        • 2021-01-17
        相关资源
        最近更新 更多