2013-07-07 16 views
2

現有的大寫字母,我用下面的代碼將每個單詞的第一個字母改爲除了一些瑣碎的那些資本(A,中等等)保持在串

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

什麼,我也想要做的是讓這些例外單詞沒有如上所述的大寫,但也有任何已經有大寫字母的單詞(例如CHINA,NSW)這些字母將被保留。

+0

即使你的問題是不夠清楚,你是顯示的代碼是沒有幫助的。第一行根本與這個問題無關。最好的例子是字符串,期望的'new_string'和當前的'new_string'。 –

+0

所以你想檢查你的字符串是否已經全部大寫......? – second

+0

「aBCDe」這個詞怎麼樣? –

回答

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. 
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. 
+0

這將刪除不需要大寫的單詞,而不是保持原樣。 – interjay

+0

@interjay謝謝你的反饋,它在列表理解中缺少一個else語句... –