【问题标题】:count words of text file in python3在python3中计算文本文件的单词
【发布时间】:2019-09-08 23:19:56
【问题描述】:

我正在学习 python,我想创建一个程序来计算文本文件中的单词总数。

fname = input("Enter file name: ") 
with open(fname,'r') as hand:
     for line in hand:
         lin = line.rstrip()
         wds = line.split()
         print(wds)
     wordCount = len(wds)
     print(wordCount)

我的文本文件的内容是: 你好这是我的测试程序 我是 python 新手 谢谢


当我在拆分后打印wds 时。 我从文本文件中获取拆分后的文本,但是当我尝试打印长度时,我只得到最后一个单词的长度。

【问题讨论】:

    标签: python


    【解决方案1】:

    您需要初始化wordCount = 0,然后在for loop 中,您需要在每次迭代时添加到wordCount。像这样的:

    wordCount = 0
    for line in hand:
        lin = line.rstrip()
        wds = lin.split()
        print(wds)
        wordCount += len(wds)
    print(wordCount)
    

    【讨论】:

      【解决方案2】:

      有四件事要做:

      • 打开一个文件
      • 从文件中读取行
      • 从行中读取单词
      • 打印字数

      所以,只需按顺序执行即可;)

      with open(fname,'r') as f:
          words = [word for line in f
                   for word in line.strip().split()]
      print(f"Number of words: {len(words)}")
      

      【讨论】:

        猜你喜欢
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        • 2014-11-04
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        • 2012-10-31
        • 1970-01-01
        相关资源
        最近更新 更多