[英]Creating a function that takes a list of words, and return a set of words in the sentence
[英]Creating a function that returns all capitalized words in a sentence (commas excluded)
我需要创建一个函数,将一个句子中的所有大写单词返回到列表中。 如果单词以逗号结尾,则需要将其排除(逗号)。 这是我想出的:
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(",", "")
也不替换逗号。 任何提示将不胜感激。
字符串是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
使用正则表达式可以做到这一点:
>>> 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']
使用re.findall
:
a= "Hellow how, Are You"
re.findall('[A-Z][a-z]+',a)
['Hellow', 'Are', 'You']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.