| | |
Help with loop
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Oct 2009
Posts: 3
Reputation:
Solved Threads: 0
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!
On down too 'Z'...
I have this down 26 times - but obviously that just doesn't work and is bad coding. Any help is greatly appreciated!
Thanks!
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)
import sys result = [] f = open("sample_text.txt") for line in f: for word in line.split(): if word.startswith('a'): result.append(word) result_length = len(set(result)) print "\nTotal DISTINCT words starting with 'a': ", result_length import sys result = [] f = open("sample_text.txt") for line in f: for word in line.split(): if word.startswith('b'): result.append(word) result_length = len(set(result)) print "Total DISTINCT words starting with 'b': ", result_length
Python Syntax (Toggle Plain Text)
import sys result = [] f = open("sample_text.txt") for line in f: for word in line.split(): if word.startswith('z'): result.append(word) result_length = len(set(result)) 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!
•
•
Join Date: Aug 2008
Posts: 165
Reputation:
Solved Threads: 49
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
Here is the script with right indent,and som print to see what happends.
my sample_text.txt
A simple fix move line 8 so it get input from loop.
Remove set
Python Syntax (Toggle Plain Text)
import sys result = [] f = open("sample_text.txt") for line in f: for word in line.split(): if word.startswith('h'): result.append(word) result_length = len(result) 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)
result = [] f = open("sample_text.txt") for line in f: for word in line.split(): if word.startswith('h'): result.append(word) print result # use print as help easier to see what happends print len(result) # use print as help easier to see what happends print "Total DISTINCT words starting with '%s' is %d" % (result[0][0], len(result)) ''' my output--> ['hi'] 1 ['hi', 'hi'] 2 ['hi', 'hi', 'hi'] 3 Total DISTINCT words starting with 'h' is 3 '''
Last edited by snippsat; Oct 1st, 2009 at 11:18 pm.
•
•
Join Date: Oct 2009
Posts: 3
Reputation:
Solved Threads: 0
Excellent! Thanks!
But is there any way to incorporate the whole alphabet into the
(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?
But is there any way to incorporate the whole alphabet into the
Python Syntax (Toggle Plain Text)
if word.startswith('x')
How would i incorporate that?
•
•
Join Date: Dec 2006
Posts: 1,035
Reputation:
Solved Threads: 293
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)
import string letter_dict = {} for letter in string.ascii_uppercase: letter_dict[letter] = 0 f = [ "abc def\n", "ghi abc def\n", "mno stuvw abc\n" ] for line in f: for word in line.strip().split(): letter = word[0].upper() letter_dict[letter] += 1 for letter in string.ascii_uppercase: print "letter %s = %d" % (letter, letter_dict[letter])
Last edited by woooee; Oct 2nd, 2009 at 12:46 am.
Linux counter #99383
![]() |
Similar Threads
- disable loop when inactive (Python)
- indented subcategory recursive loop (PHP)
- Web-Scrape Loop via CSV list of URLs ??? (Python)
- help in stored procedure-result of a loop using cursor (MS SQL)
- Excel 2007 - infinite code loop (Windows Software)
- Loop...without the loop (Java)
Other Threads in the Python Forum
- Previous Thread: complicated list return?
- Next Thread: python program
| Thread Tools | Search this Thread |
alarm assignment avogadro beginner bluetooth character cmd code customdialog cx-freeze data decimals dictionary directory dynamic error examples excel exe file float font format function generator gnu graphics gui halp homework http ideas import input itunes java leftmouse line linux list lists logging loop maintain maze module mouse number numbers output parsing path port prime programming projects push py2exe pygame pyglet pyqt python queue random recursion schedule screensaverloopinactive script scrolledtext slicenotation sqlite ssh stdout string strings sudokusolver table terminal text thread threading time tkinter tlapse tuple tutorial ubuntu unicode urllib urllib2 variable ventrilo verify vigenere web webservice wikipedia windows wxpython xlib






