esiste un metodo stringa per scrivere in maiuscolo gli acronimi in Python?
-
20-08-2019 - |
Domanda
Questo va bene:
stringa di importazione string.capwords (" nome proprio ") "Nome proprio"
Questo non è così buono:
string.capwords (quot &; & I.R.S quot;) 'I.r.s'
Non esiste un metodo stringa per eseguire le parole d'ordine in modo che si adatti agli acronimi?
Soluzione
Potrebbe funzionare:
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)
Ecco un 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."
Altri suggerimenti
No, non esiste tale metodo nella libreria standard.
Anche se ci fosse una tale funzione, cosa farebbe quando viene richiesto di elaborare " IRS " ;? Anche l'IRS si chiama & Quot; IRS & Quot; senza punti.
Ho appena usato una comprensione della lista: [". " .join ([string.capwords (l) per l in entry.split (". " )]) per l'inserimento nella lista_originale]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow