python中有没有一种字符串方法可以将首字母缩略词大写?

发布于 2024-07-12 03:58:49 字数 289 浏览 8 评论 0原文

这很好:

import string
string.capwords("proper name")

Out: 'Proper Name'

这不太好:

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

Out: 'I.r.s'

是否没有字符串方法来进行大写字母以便可以容纳首字母缩略词?

This is good:

import string
string.capwords("proper name")

Out: 'Proper Name'

This is not so good:

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

Out: 'I.r.s'

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

罗罗贝儿 2024-07-19 03:58:49

这可能有效:

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

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."
一袭白衣梦中忆 2024-07-19 03:58:49

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

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

吃颗糖壮壮胆 2024-07-19 03:58:49

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

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.

冧九 2024-07-19 03:58:49

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文