繁体   English   中英

使用 Python 计算文本文件中的行数、单词数和字符数

[英]Counting lines, words, and characters within a text file using Python

我在布置如何使用 Python 计算文本文件中的某些元素时遇到了一些困难。 我已经使用 Python 几个月了,并且熟悉以下函数;

  • 原始输入
  • 打开
  • 分裂
  • 打印
  • 拆分()

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

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')

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

尝试这个:

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')它没有意义。

可能有用的功能:

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

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

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())
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)))

我试过这段代码&它按预期工作。

我喜欢的一种方式是这种方式,但可能适用于小文件

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM