The quick brown fox
jumped over
the lazy
bear
sitting by the tree
string.strip(chars)
– removes any of the characters in chars from the beginning or end of string, returns a stringstring.split(chars)
– splits string at the chars, returns a liststring.lower()
– forces all characters to lowercase, returns a stringIt reads the file with filename, iterates over each line in the numbers.txt and return the sum. Submit your attendance.
numbers.txt
sum_numbers.py
To read a file:
To write to a file:
Use ‘a’ to append to the existing file content
Use ‘w’ to replace existing content and write to a file
You will see words.txt
in your folder.
words.txt
words.txt
words.txt
Replace line 4 and line 5 with your code
count.txt
count.txt
file_name
as argument:
count_words
count frequency of each lowercase word, return a dictionary.write_word_count
call count_words
, iterate it and write a comma separated file (“out_” + file_name
).read_and_write.py
.Test case:
def count_words(filename):
f = open(filename, "r")
counts = {}
for line in f:
words = line.strip("\n").split(" ")
for w in words:
lower_w = w.lower()
if lower_w not in counts:
counts[lower_w] = 1
else:
counts[lower_w] += 1
return counts
def write_word_count(filename):
count_dict = count_words(filename)
output_file = open("out_" + filename, "w")
for key, value in count_dict.items():
output_file.write(key + "," + str(value) + "\n")
output_file.close()
def main():
write_word_count("alien.txt")
main()