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!
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
On down too 'Z'...
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!