代码:
f = open("D:/test.txt", "r", encoding="UTF-8") content = f.read() count = content.count("itheima") print(count)
运行结果:
方法二:
代码:
count = 0 f = open("D:/test.txt", "r", encoding="UTF-8") for line in f: #一行一行读取 line = line.strip() #去除开头和结尾的空格以及换行符 words = line.split(" ") for word in words: if word == "itheima": count += 1 print(count)
结果: