File Handling Lab (i)
Scenario
A text file contains some text (nothing unusual) but we need to know how often (or how rare) each letter appears in the text. Such an analysis may be useful in cryptography, so we want to be able to do that in reference to the Latin alphabet.
Your task is to write a program which:
- asks the user for the input file's name;
- reads the file (if possible) and counts all the Latin letters (lower- and upper-case letters are treated as equal)
- prints a simple histogram in alphabetical order (only non-zero counts should be presented)
Create a test file for the code, and check if your histogram contains valid results.
Assuming that the test file contains just one line filled with:
aBcsamplefile.txt
the expected output should look as follows:
a -> 1
b -> 1
c -> 1output
Tip: We think that a dictionary is a perfect data collection medium for storing the counts. The letters may be keys while the counters can be values.
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())
myKeys.sort()
histogram= {i: histogram[i] for i in myKeys}
for x,y in histogram.items():
print(f'{x}--->{y}')
CISCO code:
from os import strerror
# Initialize 26 counters for each Latin letter.
# Note: we've used comprehension to do that.
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)}
file_name = ("text.txt")
try:
f = open(file_name, "rt")
for line in f:
print(line)
for char in line:
# If it is a letter...
if char.isalpha():
# ... we'll treat it as lower-case and update the appropriate counter.
counters[char.lower()] += 1
f.close()
# Let's output the counters.
for char in counters.keys():
cnt = counters[char]
if cnt > 0:
print(char, '->',cnt)
except IOError as e:
print("I/O error occurred: ", strerror(e.errno))
Comments
Post a Comment