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(string)
– forces all characters to lowercase, returns a stringsum_all
file_name
as argumentfile_name
in read modeSubmit your sum_all
functions to Gradescope for attendance.
Name your file sum_numbers.py
To read a file:
To write to a file: use
Use ‘a’ to append to the existing file content
Use ‘w’ to write to a file, and replace existing content
After you have opened the file in either ‘a’ or ‘w’ mode
a_file = open(file_name, mode)
Use the write function to write text content to the file
a_file.write('put this content in a file')
When finished writing, close the file a_file.close()
You have 10 minutes to complete the quiz
main()
, no need for test casesAllowed built-in functions: round()
, input()
, float()
, str()
, int()
, len()
, range()
write_word_count
file_name
as argument, it opens the file in read modeTest case:
def count_words(file_name):
f = open(file_name, "r")
counts = {}
for line in f:
words = line.strip("\n").split(" ")
for w in words:
lower_case_w = w.lower()
if lower_case_w not in counts:
counts[lower_case_w] = 1
else:
counts[lower_case_w] += 1
return counts
def write_word_count(file_name):
count_dict = count_words(file_name)
output_file = open("out_" + file_name, "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()