4 回答
TA贡献1780条经验 获得超5个赞
如果你想使用正则表达式,你可以这样做:
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
哪个输出:
1
2
4
TA贡献1719条经验 获得超6个赞
使用以下带有标志的正则表达式re.I(不区分大小写),re.findll然后返回返回列表的长度:
\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贡献1772条经验 获得超6个赞
尝试这个
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贡献1804条经验 获得超2个赞
您可以简单地将文本转换为特定大小写(即全部小写),然后使用字符串count()循环每次出现的关键字:
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
添加回答
举报