Advertisement
Guest User

Untitled

a guest
May 25th, 2015
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. # Explicit is better than implicit.
  2. # Simple is better than complex.
  3. # Complex is better than complicated.
  4.  
  5. # Above is my textfile which I've opened and added to a list, from the list I add each word into a dictionary. I'm trying to count  the amount of words which have a length of 1, 2, 3, 4. In this case: there are 0 char with a length of 1, 3 char with length of  2, 0 char with a length of 3 and 3 char with a length of 4. I'm trying to add this into a dictionary and so the below is the code:
  6.  
  7. def words_frequency(filename):
  8.     open_file = open(filename,"r")
  9.     file_text = open_file.read()
  10.     word_list = file_text.split()
  11.     open_file.close()
  12.  
  13.     word_dict = {}
  14.    
  15.     for word in word_list:
  16.         if word.isalpha():
  17.             if not word in word_dict:
  18.                 if len(word) == 1:
  19.                     word_dict[word] = 1
  20.                 elif not len(word) == 1:
  21.                     word_dict[word] = 0
  22.                
  23.                 if len(word) == 2:
  24.                     word_dict[word] = 1
  25.                 elif not len(word) == 2:
  26.                     word_dict[word] = 0
  27.                    
  28.                 if len(word) == 3:
  29.                     word_dict[word] = 1
  30.                 elif not len(word) == 3:
  31.                     word_dict[word] = 0
  32.                
  33.                 if len(word) == 4:
  34.                     word_dict[word] = 1
  35.                 elif not len(word) == 4:
  36.                     word_dict[word] = 0                
  37.             else:
  38.                 if len(word) == 1:
  39.                     word_dict[word] += 1
  40.            
  41.                 if len(word) == 2:
  42.                     word_dict[word] += 1
  43.                
  44.                 if len(word) == 3:
  45.                     word_dict[word] += 1
  46.                    
  47.                 if len(word) == 4:
  48.                     word_dict[word] += 1
  49.  
  50. #for some reason the output is:
  51.     #{'than': 3, 'Simple': 0, 'is': 2, 'Explicit': 0, 'Complex': 0, 'better': 0}
  52. #but should be:
  53.     #{'than': 3, 'Simple': 0, 'is': 3, 'Explicit': 0, 'Complex': 0, 'better': 0}
  54.  
  55. #what am I doing wrong?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement