Reputation: 1
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
Reputation: 93
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
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
Reputation: 231
with open(filename, 'r+') as f:
words = f.read()
words = words.split(' ')
words_nbr = len(words)
print(words_nbr)
Upvotes: 0
Reputation: 1463
f = open(filename) # Read
words = f.read()
f.close()
words = words.split()
print len(words)
Upvotes: 1