4 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果你想使用正則表達(dá)式,你可以這樣做:
import re
def colorcount(text):
r = re.compile(r'\bcolour\b | \bcolor\b', flags = re.I | re.X)
count = len(r.findall(text))
print(count)
return count
# These asserts work as expected without raising an AssertionError.
assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4
哪個(gè)輸出:
1
2
4

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用以下帶有標(biāo)志的正則表達(dá)式re.I(不區(qū)分大小寫(xiě)),re.findll然后返回返回列表的長(zhǎng)度:
\bcolou?r\b
import re
def colorcount(text):
return len(re.findall(r'\bcolou?r\b', text, flags=re.I))
print(colorcount('color Color colour Colour'))
印刷:
4

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試這個(gè)
def colorcount(text):
return len(re.findall('[c|C]olou{0,1}r', text))
assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以簡(jiǎn)單地將文本轉(zhuǎn)換為特定大小寫(xiě)(即全部小寫(xiě)),然后使用字符串count()循環(huán)每次出現(xiàn)的關(guān)鍵字:
def colorcount(text):
KEY_WORDS = [ 'color', 'colour' ]
counter = 0
sanitexed_text = text.lower()
for kw in KEY_WORDS:
counter += sanitexed_text.count(kw.lower())
return counter
text = 'color ds das Colour dsafasft e re Color'
# 3
print(colorcount(text))
# All following asserts pass
assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4
添加回答
舉報(bào)