有一个字符串方法利用在python首字母缩写。
-
20-08-2019 - |
题
这是良好的:
进口串 string.capwords( “专名”) '专名'
这是不那么好:
string.capwords( “I.R.S”) 'I.r.s'
有没有字符串的方法做capwords,以便它可容纳的首字母缩写
解决方案
这可能工作:
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."
其他提示
没有,存在在标准库中没有这样的方法。
即使有这样的功能,它会做什么时,要求处理“IRS”?即使是IRS自称为“IRS”,没有点。
我只是用一个列表理解:
[加入([string.capwords(升),用于升在entry.split()] “ ”),用于original_list条目“。”。]不隶属于 StackOverflow