Reputation: 1
I wrote an essay and would like to count the words in the essay using python. I pasted the essay in a python text file and saved it. I wrote a program to iterate through the text file and count the words but it keeps giving me the following error: "UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 62: character maps to <undefined>"
This is the code:
def counter(file):
with open(file) as word:
count=0
for i in word:
words=i.split()
count+=words
print(count)
The file name is essay.txt
It wont work. Even when I try to open essay.txt on the shell it doesn't work. I tried the following:
infile = open('essay.txt')
word=infile.read()
print(word)
This doesn't work either. What should i do? Please help. Thank you
Upvotes: 0
Views: 73
Reputation: 283
I tried to recreate your problem, but I was unable to do so. I have the essay.txt
file saved in the utf-8
encoding style, so that may be different from the setup you are using. The code that is working for me is as follows.
def counter(file):
with open(file) as word:
count=0
for i in word:
words=i.split()
count += len(words)
print(count)
counter("essay.txt")
I made a few changes. For each i
in word
, I believe you want the len()
function to return the total number of words on the line. You can then add the number of words on the line to the overall count for the document. This is working for me right now with Python 3.3.0. Let me know if I misunderstood!
Thanks.
Upvotes: 0
Reputation: 2952
Try
open('essay.txt', encoding ='utf-8')
It could be detected the wrong encoding type. If not utf-8 try latin1
Upvotes: 1