【问题标题】:How to use count() with text file in python如何在python中将count()与文本文件一起使用
【发布时间】:2021-06-26 06:23:00
【问题描述】:

我是一个非常困惑的初学者,想知道我应该怎么做才能完成这项工作。我的 IDE 没有给我错误,只是没有输出。

我想计算一个单词在书籍的文本文件中出现的次数,在这种情况下,“the”就是单词:

with open('heidi.txt', 'r') as file:
    content = file.read()
    content.count('the') 

【问题讨论】:

  • count 用于列表。你应该做content = file.readlines() 然后拆分列表中的每个字符串
  • 可以打电话给print(content.count("the"))吗?此外,这将在其他字符串中提取"the" 的实例,例如"there"
  • @Sujay count() 也适用于字符串,因为它是可迭代的

标签: python file text count


【解决方案1】:

count() 不打印任何内容。所以给一个变量,像这样 -

with open('heidi.txt', 'r') as file:
    content = file.read()
    a = content.count('the') 
    print(a)

【讨论】:

  • 非常感谢,这行得通,虽然我更喜欢不使用额外的变量 'a' 并使用 print(content.count('the')) 因为内容本身就是一个变量
【解决方案2】:

我学习的示例是在控制台中运行它,所以我不知道我需要使用 print()。谢谢@hilberts_drinking_problem。

with open('heidi.txt', 'r') as file:
    content = file.read()
    print(content.count('the '))

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2014-01-09
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多