更新时间:2022-10-15 23:26:09
Quick answer:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
'some string.split()
will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item)
returns the number of times item
occurs in the list.
That doesn't handle removing punctuation. You could do that using string.maketrans
and str.translate
.
# 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)
The key here is that we've constructed the string delete
so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate
in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.