创建一个返回句子中所有大写单词的函数(不包括逗号)

时间:2014-11-11 18:54:49

标签: python python-3.4

我需要创建一个函数,将句子中的所有大写单词返回到列表中。如果单词以逗号结尾,则需要将其排除(逗号)。这就是我想出的:

def find_cap(sentence):
    s = []
    for word in sentence.split():
        if word.startswith(word.capitalize()):
            s.append(word)
        if word.endswith(","):
            word.replace(",", "")
    return s

我的问题:该函数似乎有效,但是如果我有一个句子并且一个单词在引号中,即使它没有大写,它也会在引号中返回单词。即使我使用word.replace(",", ""),也不会替换逗号。任何提示将不胜感激。

3 个答案:

答案 0 :(得分:1)

字符串是Python中的不可变类型。这意味着word.replace(",", "")不会改变字符串word指向的字符串;它将返回一个替换了逗号的新字符串。

此外,由于这是一个剥离问题(并且逗号不可能在单词中间),为什么不使用string.strip()呢?

尝试这样的事情:

import string

def find_cap(sentence):
    s = []
    for word in sentence.split():

        # strip() removes each character from the front and back of the string
        word = word.strip(string.punctuation)

        if word.startswith(word.capitalize()):
            s.append(word)
    return s

答案 1 :(得分:1)

使用正则表达式执行此操作:

>>> import re
>>> string = 'This Is a String With a Comma, Capital and small Letters'
>>> newList = re.findall(r'([A-Z][a-z]*)', string)
>>> newList
['This', 'Is', 'String', 'With', 'Comma', 'Capital', 'Letters']

答案 2 :(得分:0)

使用re.findall

  a= "Hellow how, Are You"
  re.findall('[A-Z][a-z]+',a)
  ['Hellow', 'Are', 'You']