Laurence Haines
Laurence Haines

Reputation: 1

Python- Write a function that opens a .txt file and returns the total number of words in it

Been trying to do this for a while but for some reason i cant get my head around this simple code. Dont need to worry about punctuation, its just plain text. At the moment all i have is:

def wc(filename):

    f = open(filename, 'r')    # Read
    words = f.readlines()
    f.close()
    print int(filename.split())
    p = 1
    for word in words:
        p += words
    return p

been looking for an answer for a while but can only find examples where they count specific words.

Upvotes: 0

Views: 2124

Answers (4)

This one gives you lines

words = f.readlines()

You need to split word variable inside for via .split() method.

word_count += len(word.split())

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

split can take a parameter sep which specifies what characters to split on (the separator).

The string module has some constants including punctuation and whitespace.

Putting them together you get

import string

filename = 'words.txt'

with open(filename) as f:
    words = f.read().split(string.whitespace + string.punctuation)

print len(words)

Upvotes: 1

Oscar
Oscar

Reputation: 231

with open(filename, 'r+') as f:
    words = f.read()
words = words.split(' ')
words_nbr = len(words)
print(words_nbr)

Upvotes: 0

orestisf
orestisf

Reputation: 1463

f = open(filename)    # Read
words = f.read()
f.close()
words = words.split()
print len(words)

Upvotes: 1

Related Questions