[英]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.