Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Pyhthon Assignment: Reading and Writing Files fireice.txt Some say the world wil

ID: 3868559 • Letter: P

Question

Pyhthon Assignment: Reading and Writing Files

fireice.txt

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
But if it had to perish twice,
I think I know enough of hate
To say that for destruction ice
Is also great
And would suffice.

Open the file entitled fireice.txt

Use a loop and the split() command to split each line on white space, saving each token in a new file, one word per line.

Remember to add a newline character after each token so each is written to a separate line.

Open your new file, use split() again to separate each word into characters and count the number of times the letter 's' appears in the text.

Print your result in sentence form.

Remember to close files after they have been written or read.

Use comments to describe your code for credit

Explanation / Answer

#!usr/bin/python

file1 = open("fireice.txt",'r')
file2 = open("out.txt",'w')

for line in file1:
    list = line.split(' ')   // splitting to get tokens
    for i in range(len(list)):
        if ' ' in list[i]: // if the token contains ' ' , no need to append that.
          file2.write(list[i])
        else:
          file2.write(list[i] + ' ')

file1.close()
file2.close()

file2 = open("out.txt",'r')
for line in file2:
   line = line.replace(' ','') // removing ' ' from the line
   str = ' '.join(line) // forming a string from the word to split into characters
   list1 = str.split()
   count = 0
   for i in range(len(list1)):
       if list1[i] == 's':
          count = count + 1
   print(line + ": s appeared " ,count, " times")
file2.close()