快速回答:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
‘some string.split()会将空格(空格,制表符和换行符)上的字符串拆分为单词列表.然后[‘some’,’string’].count(item)返回项目在列表中出现的次数.
# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))
def count_occurrences(word, sentence):
return sentence.lower().translate(table, delete).split().count(word)
这里的关键是我们构造了字符串delete,以便它包含除字母,数字和空格之外的所有ascii字符.然后str.translate在这种情况下采用一个不改变字符串的转换表,而且还要删除一串字符.