File Handling (ii)
Scenario
The previous code needs to be improved. It's okay, but it has to be better.
Your task is to make some amendments, which generate the following results:
- the output histogram will be sorted based on the characters' frequency (the bigger counter should be presented first)
- the histogram should be sent to a file with the same name as the input one, but with the suffix '.hist' (it should be concatenated to the original name)
Assuming that the input file contains just one line filled with:
cBabAasamplefile.txt
the expected output should look as follows:
a -> 3
b -> 2
c -> 1output
Tip: Use a lambda to change the sort order
Python sorted() key
sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value. For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len() function as key, then the strings would be passed to len(), and the value it returns, i.e. the length of strings will be sorted. This means that the strings would be sorted based on their lengths instead
- Python3
Output:
Normal sort : ['aaa', 'b', 'cccc', 'dd'] Sort with len : ['b', 'dd', 'aaa', 'cccc']
Key can also take user-defined functions as its value for the basis of sorting.
Mycode:
a="text.txt"
histogram={}
try:
b=open(a,"rt")
except IOError as e:
print("no",strerror(e.errno))
exit(e.errno)
c=b.read().replace(" ","")
c=c.lower()
for i in c:
if i not in histogram.keys() and ord('a')<=ord(i)<=ord('z'):
histogram[i]=c.count(i)
myKeys = list(histogram.keys())
# commented out parts of previous code not needed
#myKeys.sort()
#histogram= {i: histogram[i] for i in myKeys}
#print(histogram)
#print([a for a in range(ord('a'),ord('z')+1)])
#for x,y in histogram.items():
# print(f'{x}--->{y}')
my_values=list(histogram.values())
my_values.sort(reverse=True)
###copying histogram to new file
name=a.replace('.txt','.hist')
dst_file=open(name,'w')
for i in my_values:
for j in [chr(a) for a in range(ord('a'),ord('z')+1)] and myKeys:
if histogram[j]==i:
k=f'{j}--->{i}'
#print(k)
dst_file.write(k+'\n') #\n since write continues from last spot and doesn't add \n on it's own
#checking if successfully copied
dst_file.close()
dst_file=open(name,'r')
a=dst_file.read()
print(a)
CISCO:
rom os import strerror
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)}
file_name = input("Enter the name of the file to analyze: ")
try:
f = open(file_name, "rt")
for line in f:
for char in line:
if char.isalpha():
counters[char.lower()] += 1
f.close()
f = open(file_name + '.hist', 'wt')
# Note: we've used lambda to access the directory's elements and set reverse to get a valid order.
for char in sorted(counters.keys(), key=lambda x: counters[x], reverse=True):
cnt = counters[char]
if cnt > 0:
f.write(char + ' -> ' + str(cnt) + '\n')
f.close()
except IOError as e:
print("I/O error occurred: ", strerror(e.errno))
Comments
Post a Comment