【问题标题】:Counting lines, words, and characters within a text file using Python使用 Python 计算文本文件中的行数、单词和字符
【发布时间】:2011-01-24 15:45:30
【问题描述】:

我在阐述如何使用 Python 计算文本文件中的某些元素时遇到了一些麻烦。我已经使用 Python 几个月了,我熟悉以下功能;

  • 原始输入
  • 打开
  • 拆分
  • 长度
  • 打印
  • rsplit()

到目前为止,这是我的代码:

fname = "feed.txt"
fname = open('feed.txt', 'r')

num_lines = 0
num_words = 0
num_chars = 0

for line in feed:
    lines = line.split('\n')

在这一点上,我不确定下一步该做什么。我觉得最合乎逻辑的方法是先计算行数,计算每行中的单词,然后计算每个单词中的字符数。但是我遇到的一个问题是尝试一次执行所有必要的功能,而不必重新打开文件来单独执行每个功能。

【问题讨论】:

  • 我想你的意思是'feed = open(...)`。另外,有理由不使用wc吗?
  • 你是对的。我也会详细了解如何使用“wc”,谢谢你的链接。

标签: python


【解决方案1】:

试试这个:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

回到你的代码:

fname = "feed.txt"
fname = open('feed.txt', 'r')

这有什么意义? fname 首先是一个字符串,然后是一个文件对象。您并没有真正使用第一行中定义的字符串,您应该只将一个变量用于一件事:字符串或文件对象。

for line in feed:
    lines = line.split('\n')

line 是文件中的一行。 split('\n')它没有意义。

【讨论】:

  • 欣赏故障。我以为我需要添加 '\n' 来分解每一行,但似乎 line.split() 完成了我的意图。
  • @Alex Karpowitsch:在for line in file 中迭代文件会将文件分成几行。 line.split() 将一行变成文字。
  • wc 的字符数至少也包括换行符(并且它的 »character« 计数始终是文件的字节长度(即使对于 UTF-16 也是如此)。所以,实际上一个克隆它可能需要一些工作,这取决于 OP 是否是这样。
  • 是的,刚刚注意到 - 我用 num_char 少了 20 个字符。当我应该得到 736 时,它得到了 756。
【解决方案2】:

可能有用的功能:

  • open("file").read() 一次读取整个文件的内容
  • 'string'.splitlines() 将行彼此分隔(并丢弃空行)

通过使用 len() 和那些函数,你可以完成你正在做的事情。

【讨论】:

    【解决方案3】:
    fname = "feed.txt"
    feed = open(fname, 'r')
    
    num_lines = len(feed.splitlines())
    num_words = 0
    num_chars = 0
    
    for line in lines:
        num_words += len(line.split())
    

    【讨论】:

      【解决方案4】:
      file__IO = input('\nEnter file name here to analize with path:: ')
      with open(file__IO, 'r') as f:
          data = f.read()
          line = data.splitlines()
          words = data.split()
          spaces = data.split(" ")
          charc = (len(data) - len(spaces))
      
          print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))
      

      我尝试了这段代码,它按预期工作。

      【讨论】:

        【解决方案5】:

        我喜欢这种方式之一,但可能对小文件有好处

        with open(fileName,'r') as content_file:
            content = content_file.read()
            lineCount = len(re.split("\n",content))
            words = re.split("\W+",content.lower())
        

        计算单词有两种方法,如果你不关心重复,你可以这样做

        words_count = len(words)
        

        如果你想要每个单词的计数,你可以这样做

        import collections
        words_count = collections.Counter(words) #Count the occurrence of each word
        

        【讨论】:

          猜你喜欢
          • 2013-02-20
          • 1970-01-01
          • 2023-03-12
          • 2018-06-02
          • 1970-01-01
          • 2023-03-16
          • 2014-11-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多