Help with loop

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Oct 2009
Posts: 3
Reputation: walker164 is an unknown quantity at this point 
Solved Threads: 0
walker164 walker164 is offline Offline
Newbie Poster

Help with loop

 
-1
  #1
Oct 1st, 2009
Hi everyone,

I'm working on a homework assignment and i'm brand new to python (i'm a better c++ coder). Anyway, I've used help from classmates and google to compile this code chunk and i need to know how i can make this into a loop so i dont have 26 code chunks.

This code chunks reads a bunch of text from a file and looks at each word and determines fi it begins with 'x' letter (a or b...etc) and then prints out its frequency.

So basically i'm looking for the number of words, in the text, that begin with this letter and that letter.

Thanks for your help!

  1. import sys
  2. result = []
  3. f = open("sample_text.txt")
  4. for line in f:
  5. for word in line.split():
  6. if word.startswith('a'):
  7. result.append(word)
  8. result_length = len(set(result))
  9. print "\nTotal DISTINCT words starting with 'a': ", result_length
  10.  
  11. import sys
  12. result = []
  13. f = open("sample_text.txt")
  14. for line in f:
  15. for word in line.split():
  16. if word.startswith('b'):
  17. result.append(word)
  18. result_length = len(set(result))
  19. print "Total DISTINCT words starting with 'b': ", result_length
On down too 'Z'...
  1. import sys
  2. result = []
  3. f = open("sample_text.txt")
  4. for line in f:
  5. for word in line.split():
  6. if word.startswith('z'):
  7. result.append(word)
  8. result_length = len(set(result))
  9. print "Total DISTINCT words starting with 'z': ", result_length

I have this down 26 times - but obviously that just doesn't work and is bad coding. Any help is greatly appreciated!

Thanks!
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 167
Reputation: snippsat is an unknown quantity at this point 
Solved Threads: 49
snippsat's Avatar
snippsat snippsat is offline Offline
Junior Poster

Re: Help with loop

 
1
  #2
Oct 1st, 2009
indentations is 4 spaces,it work with 2 and 8 but never ever us anything else than 4.

A simple fix move line 8 so it get input from loop.
Remove set
  1. import sys
  2. result = []
  3. f = open("sample_text.txt")
  4. for line in f:
  5. for word in line.split():
  6. if word.startswith('h'):
  7. result.append(word)
  8. result_length = len(result)
  9. print "Total DISTINCT words starting with 'z': ", result_length

Here is the script with right indent,and som print to see what happends.

my sample_text.txt
hi this is an test.
hi again why not.
hi number 3.

  1. result = []
  2. f = open("sample_text.txt")
  3. for line in f:
  4. for word in line.split():
  5. if word.startswith('h'):
  6. result.append(word)
  7. print result # use print as help easier to see what happends
  8. print len(result) # use print as help easier to see what happends
  9. print "Total DISTINCT words starting with '%s' is %d" % (result[0][0], len(result))
  10.  
  11. '''
  12. my output-->
  13. ['hi']
  14. 1
  15. ['hi', 'hi']
  16. 2
  17. ['hi', 'hi', 'hi']
  18. 3
  19. Total DISTINCT words starting with 'h' is 3
  20. '''
Last edited by snippsat; Oct 1st, 2009 at 11:18 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 3
Reputation: walker164 is an unknown quantity at this point 
Solved Threads: 0
walker164 walker164 is offline Offline
Newbie Poster

Re: Help with loop

 
0
  #3
Oct 1st, 2009
Excellent! Thanks!

But is there any way to incorporate the whole alphabet into the
  1. if word.startswith('x')
(replacing the spot of x with a-z) statement so i dont have to have 26 separate statements? Because i need to find the number of words that begin with every letter.

How would i incorporate that?
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 1,045
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 293
woooee woooee is offline Offline
Veteran Poster

Re: Help with loop

 
1
  #4
Oct 2nd, 2009
A dictionary with the letter as the key is the straight forward way to do this. Otherwise use a function with a for loop to pass the letter and the string to the function.
  1. import string
  2.  
  3. letter_dict = {}
  4. for letter in string.ascii_uppercase:
  5. letter_dict[letter] = 0
  6.  
  7. f = [ "abc def\n",
  8. "ghi abc def\n",
  9. "mno stuvw abc\n" ]
  10.  
  11. for line in f:
  12. for word in line.strip().split():
  13. letter = word[0].upper()
  14. letter_dict[letter] += 1
  15.  
  16. for letter in string.ascii_uppercase:
  17. print "letter %s = %d" % (letter, letter_dict[letter])
Last edited by woooee; Oct 2nd, 2009 at 12:46 am.
Linux counter #99383
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 3
Reputation: walker164 is an unknown quantity at this point 
Solved Threads: 0
walker164 walker164 is offline Offline
Newbie Poster

Re: Help with loop

 
0
  #5
Oct 2nd, 2009
Thanks buddy!

That is some code i would have never been able to write in 10 years. Very nice. Thanks so much for your help
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC