File handling exercise(2-grams)

hi ,
in the exercise of file handling,in the third question,according to the solution provided by sir ,we will get a list of tuples consisting 2 words as 2 individual there any code to convert that tuple as a single string as we done in the previous problem where we joined all words as a single string.i tried it by initializing a list of strings and followed the previous steps (join() function),but i am not sure about the approach .if any solutions with this approach please reply.
the code i wrote was:


for i in range(len(two_grams)):

gram_str[i]=" ".join(two_grams[i])
the error i am getting is

IndexError Traceback (most recent call last)
in ()
2 i=0
3 for i in range(len(two_grams)):
----> 4 gram_str[i]=" ".join(two_grams[i])

IndexError: list assignment index out of range

would appreciate all help

Hi Pranava Chanakya,
The following is my approach to the solution… as you see it is completely different from Professor’s. But it works and simple to understand.

From the previous exercise all words stored in list poemwords

Create list with 2 grams

wcount = len (poemwords)
my2grams = [ ]
x = poemwords [0]

while i <= wcount-1:
y = poemwords[i]
x = y

Create a uniqe list of 2 grams

for i in range(len(my2grams)):
if my2grams[i] not in uniquelist:

update the number of times 2 grams repeated in the poem.txt

for i in range(len(uniquelist)):
x = my2grams.count(uniquelist[i])

#sort the list in decending order
finallist = sorted(uniquelist, key=lambda x: x[2], reverse=True)

#Display the Top 10 2 grams appear in the poem.txt after sorting. Same count 2 grams are ordered, may get
#excluded if the numbers exceed more than 10.
#Output is stored in a text file most2gram.txt
with open (“most2gram.txt”, mode=“w”, encoding=‘utf-8’) as f:
f.writelines ("----------------------------\n")
f.writelines (“Count\t2 gram Word\n”)
f.writelines ("----------------------------\n")
for i in range(10):
f.writelines (str(finallist[i][2])+"\t"+finallist[i][0]+"\t"+finallist[i][1]+"\n")
f.writelines ("----------------------------\n")

1 Like


Assignment to an indexed element of a list only works if the list already has an element at that index, and you want to change it.
So, if gram_str[i] already possessed some value, the code you gave could be used to assign to it.
However, you have initialized gram_str to an empty list, so there is nothing there, even for an index of 0.
What you want to do is append
" ".join(two_grams[i])
to the end of gram_str, not assign it to an existing element. So you should use
gram_str.append(" ".join(two_grams[i]))
instead of
gram_str[i] = " ".join(two_grams[i])