2014-01-19 31 views
-5

下面的代码大写了“w”中单词的第一个单词。我想知道函数captilize(句子)是如何工作的?具体来说,sentence.split是做什么的?使用python代码对一个句子中第一个字母的大写字母

`

import random 

def test(): 
    w = ["dog", "cat", "cow", "sheep", "moose", "bear", "mouse", "fox", "elephant", "rhino", "python"] 
    s = "" 

    #random.seed(rnd_seed) 

    for i in range(0, random.randint(10,15)): 
    s += random.choice(w) + " " 
    print "<ignore>Sentence: " + s 
    print "Capitalized: " + capitalize(s).strip() 


def capitalize(sentence): 
    w = sentence.split() 
    ww = "" 
    for word in w: 
    ww += word.capitalize() + " " 
    return ww 


test()` 
+0

在一个交互式Python提示符,尝试'帮助(“”分割)' –

+0

你永远不会了解,如果你不尝试。这个问题必须关闭,因为它没有显示对代码的最小理解。 –

+0

正如@Anonymous所说,你自己做点什么,就像在你的Python提示符中尝试帮助命令一样。 –

回答

0

.split(SEP): 具体分裂方法以一个字符串并返回的词的列表字符串中,使用月作为分隔符串。如果没有分隔符值被传递,则将空格作为分隔符。

例如:

a = "This is an example" 
a.split()  # gives ['This', 'is', 'an', 'example'] -> same as a.split(' ') 

谈论你的功能,它需要一个字符串形式的句子,每个单词大写返回的句子。让我们来看看它逐行:

def capitalize(sentence): # sentence is a string 
    w = sentence.split()  # splits sentence into words eg. "hi there" to ['hi', there'] 
    ww = ""     # initializes new string to empty 
    for word in w:     # loops over the list w 
    ww += word.capitalize() + " "  # and capitalizes each word and adds to new list ww 
    return ww        # returns the new list 
相关问题