且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何计算一个单词在一个句子中出现的次数? (蟒蛇)

更新时间: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.

相关阅读

技术问答最新文章