By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,957 Members | 2,038 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,957 IT Pros & Developers. It's quick & easy.

How to handle or skip end‐of‐line characters

P: 3
I am trying to read from a txt file and counts the number of times each word appears. The problem is that it counts the EOL characters as well. I want to skip them. I tried to use the rstrip, still it didn't do anything. So how can I handle these end-of-line characters?

I am using python 3.

Please help.

Expand|Select|Wrap|Line Numbers
  2. Object= open('w.txt','r')
  3. L=
  5. occurrenences={}
  6. for word in L.split():    
  7.     occurrenences[word] = occurrenences.get(word,0)+1
  9. for word in occurrenences:    
  10.     print(occurrenences[word],word)
  12. Object.close()
Mar 21 '11 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 2.5K+
P: 2,851
Iterate on the file object instead of reading the file all at once.
Expand|Select|Wrap|Line Numbers
  1. f = open('w.txt')
  2. dd = {}
  3. for line in f:
  4.     words = line.strip().split()
  5.     for word in word:
  6.         dd[word] = dd.get(word, 0) + 1
  7. f.close()
Mar 22 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.