Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I'm having a bit of a rough time laying out how I would count certain elements within a text file using Python. I'm a few months into Python and I'm familiar with the following functions;

  • raw_input
  • open
  • split
  • len
  • print
  • rsplit()

Here's my code so far:

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

At this point I'm not sure what to do next. I feel the most logical way to approach it would be to first count the lines, count the words within each line, and then count the number of characters within each word. But one of the issues I ran into was trying to perform all of the necessary functions at once, without having to re-open the file to perform each function seperately.

like image 432
Alex Karpowitsch Avatar asked Jan 24 '11 15:01

Alex Karpowitsch


2 Answers

Try this:

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)

Back to your code:

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

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

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

line is one line from the file. It does not make sense to split('\n') it.

like image 81
eumiro Avatar answered Oct 07 '22 17:10

eumiro


Functions that might be helpful:

  • open("file").read() which reads the contents of the whole file at once
  • 'string'.splitlines() which separates lines from each other (and discards empty lines)

By using len() and those functions you could accomplish what you're doing.

like image 30
kynnysmatto Avatar answered Oct 07 '22 18:10

kynnysmatto