This program find the number of occurrences of each word in a file assuming that each line contains one word only. It is a simple prog.
def x():
file = open('input.txt', "r")
file1 = open('output.txt', 'w')
lines = file.readlines()
dictionary = {}
list = []
for line in lines:
if dictionary.has_key(line.strip()):
dictionary[line.strip()] += 1
else:
dictionary[line.strip()] = 1
keys1 = dictionary.keys()
keys1.sort()
for i in range(0, len(keys1)):
key1 = keys1[i].rjust(5)
val1 = dictionary[keys1[i].strip()]
list.append([key1, val1])
list.sort(lambda x,y: cmp(y[1], x[1]))
for i in range(0, len(keys1)):
str1 = list[i][0] +" "+ str(list[i][1]) + "\n"
file1.write(str1)
file.close()
file1.close()
It uses a lot memory since we are creating list, keys list and dictionary each is size of number of words in file.
-
Purush
Great post
ReplyDeleteI have found a similar post for
https://traveltimings.in/hyderabad-medak/
https://traveltimings.in/jbs-yadagirigutta/
https://traveltimings.in/jbs-vemulawada/