Julian Julian - 7 months ago 21
Python Question

Getting ord() to read from a file

What my code does is it counts the amount of times a letter has appeared and counts it to the respected letter. So if A appears two times, it will show 2:A. My problem is that i want it to read from a file and when ord() tries to, it cant. I dont know how to work around this.

t=open('lettersTEst.txt','r')
tList=[0]*26
aL=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

idx=0


for char in t:
ch=ord(char)
if ch >=65 and ch <= 90:
pos=int(ch)-65
tList[pos]+=1

for ele in tList:
print(idx, ": ", tList[ch])
idx+=1

Answer

When you iterate over a file you get lines. If you want characters you need to iterate over each line as well.

for line in t:
    for char in line:
        ch = ord(char)
        ...