您可以使用,
str.count()因为您只关心单个单词的出现:
with open("log_file") as f: contents = f.read() count = contents.count("apple")但是,为避免出现一些极端情况,例如错误地计数像这样的单词
"applejack",我建议您使用正则表达式:
import rewith open("log_file") as f: contents = f.read() count = sum(1 for match in re.finditer(r"bappleb", contents))b在正则表达式中,确保模式在 单词边界处 开始和结束(与较长字符串中的子字符串相对)。



