Define a function called ngram_list() that takes a filename and a positive integer n representing the number of characters to be displayed on each line (but don't actually display anything in this function — so no print() in this function). The function should return a list of strings, consisting of the contents of the file split into chunks n characters long. If there is an error working with the file, the function should return an empty list.
For example, using the same file as before, the command ngram_list("hanlon.txt",20) should return the list["Never attribute to m", "alice that which is ", "adequately explained", " by stupidity."]
def ngram_list(file,n):
try:
f=open(file)
text=f.read()
print(text)
data=[]
k=0
token=""
for i in text:
token+=i
k+=1
if k==n:
data.append(token)
k=0
token=''
if k!=0:
data.append(token)
f.close()
return data
except:
return []
return []
Get Answers For Free
Most questions answered within 1 hours.