In: Computer Science
How to print output vertically in the code attached below:
import operator with open ('The Boy .txt',encoding='utf8') as my_file: contents=my_file.read() l = contents.strip() words = l.split() newdict = dict() for i in words: if i in newdict: newdict[i] = newdict[i] + 1 else: newdict[i] = 1 newly = dict() sorted_Dict = sorted(newdict.items(), key=operator.itemgetter(1), reverse=True) for n in sorted_Dict: newly[n[0]] = n[1] print(newly) with open('freqs.txt','w', encoding='utf8') as final: final.write(str(newly))
CODE:
file.txt
:
OUTPUT:
Note : ls command is used to
list the files in the current directory.
freqs.txt :
RAW CODE:
import operator
with open ('file.txt',encoding='utf8') as my_file:
contents=my_file.read()
l = contents.strip()
words = l.split()
newdict = dict()
for i in words:
if i in newdict:
newdict[i] = newdict[i] + 1
else:
newdict[i] = 1
sorted_Dict = sorted(newdict.items(), key=operator.itemgetter(1), reverse=True) # sorting dictionary
with open('freqs.txt','w', encoding='utf8') as final: # opening file
for n in sorted_Dict: # iterate each pair in sorted_Dict
print(str(n[0]) + "\t" + str(n[1])) # printing each pair vertically separated by tab space into console
final.write(str(n[0] + "\t" + str(n[1])) + "\n") # writing each pair vertically separated by tab space into file
NOTE:
If You have any doubts feel free to comment in comment
section.
DO VOTE(LIKE).