2016-11-15 54 views
2

這裏是我的代碼:善用每個句子的第一個字母在Python

def fix_capitalization(usrStr): 
    newString = '' 
    wordList = [] 
    numLetters = 0 
    for s in usrStr.split('. '): 
     if s[0].isupper(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(s) 
     if s.islower(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(s) 
      numLetters += 1 

     if s[0].islower(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(s) 
      numLetters += 1 



    newString = '. '.join(wordList) 
    return newString, numLetters 

中所傳遞的字符串是:

i want some water. he has some. maybe he can give me some. i think I will ask.

注意,有maybe前4位。我需要的結果是:

I want some water. He has some. Maybe he can give me some. I think I will ask.

,但我得到:

I want some water. He has some. maybe he can give me some. I think I will ask.

我知道maybe沒有被資本化,因爲我劈在.和這句話有一個以上這段時間後的空間,但我不知道我該如何解決這個問題,或者如果有更好的方式去做我正在做的事情。任何幫助將不勝感激。

+1

你想之前,「也許」保留4空間或者更改標準1個空間? – Skycc

+0

@Skycc我想保留4個空格。剛剛通過某人的幫助編輯了我的問題,所以更清楚。 – Kblo55

+0

http://stackoverflow.com/questions/26320697/capitalization-of-each-sentence-in-a-string-in-python-3 –

回答

0

在for循環: 首先找到非空格字符的索引。 然後用s [index]替換s [0]。

+0

我試圖做到這一點,但無法讓它工作。你能解釋一下,如果你不介意,我會怎麼做? – Kblo55

+1

http://stackoverflow.com/questions/2378962/returning-the-lowest-index-for-the-first-non-whitespace-character-in-a-string-in –

+0

幫助我找到索引,但第一部分我無法弄清楚如何用大寫版本替換索引。 – Kblo55

0

解決方案使用正則表達式子方法

def fix_capitalization(mystr): 
    numLettets = 0 
    newstr = [] 
    for s in mystr.split('. '): 
     tmp = re.sub('^(\s*\w+)', lambda x:x.group(1).title(), s) 
     newstr.append(tmp) 
     # num of letters 
     if s.lstrip()[0] != tmp.lstrip()[0]: 
      numLetters += 1   
    return '. '.join(newstr).replace(' i ', ' I '), numLetters 

fix_capitalization('i want some water. he has some. maybe he can give me some. i think I will ask.') 
# return ('I want some water. He has some. Maybe he can give me some. I think I will ask.', 4) 

簡單的修復到原來的代碼如下

def fix_capitalization(usrStr): 
    newString = '' 
    wordList = [] 
    numLetters = 0 
    for s in usrStr.split('. '): 
     # check for leading space 
     lspace = len(s) - len(s.lstrip()) 
     s = s.lstrip() 

     if s[0].isupper(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(' '*lspace + s) 
     if s.islower(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(' '*lspace + s) 
      numLetters += 1 
     if s[0].islower(): 
      s = s.capitalize() 
      s = s.replace(' i ', " I ") 
      wordList.append(' '*lspace + s) 
      numLetters += 1 

    newString = '. '.join(wordList) 
    return newString, numLetters 
相關問題