python - 一个词在一个文件中出现了多少次?

标签 python

在我的 Python 作业中,我的作业是:“编写一个完整的 python 程序,读取文件 trash.txt 并输出单词 Bob 在文件中出现的次数。”

我的代码是:

count=0
f=open('trash.txt','r')
bob_in_trash=f.readlines()
for line in bob_in_trash:
    if "Bob" in line:
        count=count+1
print(count)
f.close()

有没有办法让这段代码更有效率?它正确地计数为 5,但我想知道是否有任何我可以修改的地方。

最佳答案

你可以读取整个文件并计算“Bob”的数量:

data = open('trash.txt').read()
count = data.count('Bob')

虽然这对于较小的文件更准确,但是当您处理较大的文件时,将整个文件加载到内存中可能会出现问题。

逐行读取仍然更有效率,但使用 str.count 而不是 Bob in line(这会让你读取多少行有“Bob”里面)。

with open('trash.txt') as f:
    for line in f:
        count += line.count("Bob")

关于python - 一个词在一个文件中出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414989/

相关文章:

python - 如何重新安排 403 HTTP 状态代码稍后在 scrapy 中抓取?

python - 返回 python 列表中匹配项的值

c++ - 为科学代码选择前端/解释器

python - wtforms+flask 今天的日期作为默认值

python 的 re : replace regex to regex

python - Django Rest 框架序列化程序关系 : How to get a list of only the latest track?

python - 使用 selenium 抓取多个页面

python - 简单逻辑 Python 3

python - Pymongo replace_one modified_count 总是 1 即使没有改变任何东西

python - Django:RelatedManager 对象是如何实例化的?