2

我正在使用以下代码将每个单词的第一个字母更改为大写字母,除了一些琐碎的(a、of 等)

f = open('/Users/student/Desktop/Harry.txt').readlines()[2]
new_string = f.title()
print (new_string)

我还想做的是让那些例外词不如上所述大写,但也有任何已经有大写字母的词(例如中国,新南威尔士州),这些字母将被保留。

4

2 回答 2

1

像这样的东西:

使用str.capitalize

为什么?

>>> "CAN'T".title()
"Can'T"

>>> "CAN'T".capitalize()
"Can't"

代码:

>>> strs = """What i would also like to do is have those exception words not capitalised as 
stated above but also have that any word that already has capitals letters
( For e.g. CHINA, NSW etc. ) that those letters will be retained."""
>>> words = {'a','of','etc.','e.g.'}  #set of words that shouldn't be changed
>>> lis = []
for word in strs.split():
    if word not in words and not word.isupper(): 
        lis.append(word.capitalize())
    else:    
        lis.append(word)
...         
>>> print " ".join(lis)
What I Would Also Like To Do Is Have Those Exception Words Not Capitalised As Stated Above But Also Have That Any Word That Already Has Capitals Letters ( For e.g. CHINA, NSW etc. ) That Those Letters Will Be Retained.
于 2013-07-07T10:49:33.427 回答
0

对于第一个要求,您可以创建一个包含异常词的列表:

e_list = ['a', 'of', 'the'] # for example

然后你可以运行这样的东西,isupper()用来检查字符串是否已经全部大写:

new = lambda x: ' '.join([a.title() if (not a in e_list and not a.isupper()) else a for a in x.split()])

测试:

f = 'Testing if one of this will work EVERYWHERE, also in CHINA, in the run.'

print new(f)
#Testing If One of This Will Work EVERYWHERE, Also In CHINA, In the Run.
于 2013-07-07T10:47:13.460 回答