943,985 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 437
  • Python RSS
Oct 1st, 2009
-1

Help with loop

Expand Post »
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!

Python Syntax (Toggle Plain Text)
  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'...
Python Syntax (Toggle Plain Text)
  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!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
walker164 is offline Offline
3 posts
since Oct 2009
Oct 1st, 2009
1

Re: Help with loop

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
Python Syntax (Toggle Plain Text)
  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.

Python Syntax (Toggle Plain Text)
  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.
Reputation Points: 280
Solved Threads: 278
Master Poster
snippsat is offline Offline
771 posts
since Aug 2008
Oct 1st, 2009
0

Re: Help with loop

Excellent! Thanks!

But is there any way to incorporate the whole alphabet into the
Python Syntax (Toggle Plain Text)
  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?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
walker164 is offline Offline
3 posts
since Oct 2009
Oct 2nd, 2009
1

Re: Help with loop

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.
Python Syntax (Toggle Plain Text)
  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.
Reputation Points: 741
Solved Threads: 692
Nearly a Posting Maven
woooee is offline Offline
2,307 posts
since Dec 2006
Oct 2nd, 2009
0

Re: Help with loop

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
Reputation Points: 10
Solved Threads: 0
Newbie Poster
walker164 is offline Offline
3 posts
since Oct 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: complicated list return?
Next Thread in Python Forum Timeline: python program





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC