| | |
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!
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,045
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
- Excel 2007 - infinite code loop (Windows Software)
- 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)
- 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 |
abrupt ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd code customdialog data decimals dictionaries dictionary drive dynamic error examples excel exe file float format function gnu graphics gui heads homework http ideas import input java launcher leftmouse line linux list lists logging loop module mouse number numbers output parsing path pointer port prime programming progressbar projects push py2exe pygame pyqt python random recursion schedule script scrolledtext sqlite statistics stdout string strings sudokusolver sum table terminal text thread threading time tkinter tlapse tricks tuple tutorial twoup ubuntu unicode update urllib urllib2 variable wikipedia windows write wxpython xlib






