How to handle or skip end‐of‐line characters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nana pink
    New Member
    • Mar 2011
    • 3

    How to handle or skip end‐of‐line characters

    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.

    Code:
     
    Object= open('w.txt','r')
    L= Object.read().rstrip()
    
    occurrenences={}
    for word in L.split():    
        occurrenences[word] = occurrenences.get(word,0)+1
    
    for word in occurrenences:    
        print(occurrenences[word],word)
    
    Object.close()
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Iterate on the file object instead of reading the file all at once.
    Code:
    f = open('w.txt')
    dd = {}
    for line in f:
        words = line.strip().split()
        for word in word:
            dd[word] = dd.get(word, 0) + 1
    f.close()

    Comment

    Working...