Week 5 -File Handling -Write 1

I am getting the below errors for the below inputs:

  1. for i in range(length):
    lines[i]=lines[i].replace(’\n’,’’ )

Error:

TypeError Traceback (most recent call last)
in ()
1 for i in range(length):
----> 2 lines[i]=lines[i].replace(’\n’,’’ )##ask

TypeError: a bytes-like object is required, not 'str

  1. chars_to_replace=[’\n’,’,’,’-’]
    for i in range(length):
    for s in chars_to_replace:
    lines[i]=lines[i].replace(s,’’)

Error:

TypeError Traceback (most recent call last)
in ()
2 for i in range(length):
3 for s in chars_to_replace:
----> 4 lines[i]=lines[i].replace(s,’’)

TypeError: a bytes-like object is required, not ‘str’

  1. text=""
    for line in lines:
    text+=line+" "

Error:

TypeError Traceback (most recent call last)
in ()
1 text=""
2 for line in lines:
----> 3 text+=line+" "##ask

TypeError: can’t concat str to bytes

  1. text=" ".join(lines)

error:

TypeError Traceback (most recent call last)
in ()
----> 1 text=" ".join(lines)

TypeError: sequence item 0: expected str instance, bytes found

  1. print(len(words),words)

Output:
0

  1. print(word_freq)
    Output:
    {}

  2. print(sorted(word_freq))
    Output:

  3. print(sorted(word_freq.items()))

output:

  1. print(sorted(word_freq.items(), key=lamda item: item[0]))

Output:

File “”, line 1
print(sorted(word_freq.items(), key=lamda item: item[0])) ####ask
^
SyntaxError: invalid syntax

  1. print(sorted(word_freq.items(), key=lamda item: item[1]))

output:
File “”, line 1
print(sorted(word_freq.items(), key=lamda item: item[0])) ####ask
^
SyntaxError: invalid syntax

  1. print(sorted(word_freq.items(), key=lamda item: item[1]))

output:

File “”, line 1
print(sorted(word_freq.items(), key=lamda item: item[1])) ####ask
^
SyntaxError: invalid syntax

  1. sorted_list[-10]

output:


NameError Traceback (most recent call last)
in ()
----> 1 sorted_list[-10]

NameError: name ‘sorted_list’ is not defined

  1. with open(‘most_common_words.txt’,‘w’) as f_out:
    for item in sorted_list[-10]:
    f_out.write(item[0] + “\n”)

output:


NameError Traceback (most recent call last)
in ()
1 with open(‘most_common_words.txt’,‘w’) as f_out:
----> 2 for item in sorted_list[-10]:
3 f_out.write(item[0] + “\n”)

NameError: name ‘sorted_list’ is not defined

For these two errors, it says that the given list is of type byte, as the file is opened in binary mode.
Please open file with ‘r’ mode instead of ‘rb’ mode.
Use the following snippet to open the file:

with open(fname, 'r') as f:

It seems most of the errors just need this change to get resolved. Please try the above snippet, and let me know if there’s any of them still coming.

Input:
with open(For Padhai.txt,‘r’) as f:

Error:
File “”, line 1 with open(For Padhai.txt,‘r’) as f: ^ SyntaxError: invalid syntax

Pass file name as a string.

with open("For Padhai.txt" , ‘r’) as f: