0
file=open("apple.txt","r")
letters=0
for line in file:
 words=line.split()
 for character in words:
     character = int(character)
     if character<=90 and character>=65:            #ascii code for the uppercase letters
         letters+=1
     elif character<=122 and character>=97:         #ascii code for lowercase letters
         letters+=1
print(letters)

The error i get is if int(character)<=90 and int(character)>=65:ValueError: invalid literal for int() with base 10: 'I' Im not too sure what. Also my txt file contains I ate apples. 123 I am trying to make it so it will only count the letters I ate apples so I should see only see 10 letters when the program goes through. If someone can help with this it would be much appreciated.

  • 2
    To convert a char (more exactly a string of length 1) to an integer you need `ord()`, not `int()`. But why convert at all? Just do `'A' <= character <= 'Z' or 'a' <= character <= 'z'` – gimix Oct 13 '22 at 16:10
  • `for character in words` should be `for word in words` ...no? – Anentropic Oct 13 '22 at 16:11

2 Answers2

0

The function you need is ord instead of int, because you want to get the ASCII value of a character.

For example, ord("A") will give 65.

file=open("apple.txt","r")
letters=0
for line in file:
 words=line.split()
 for character in words:
     character = ord(character) # Get ASCII value associated with this character
     if character<=90 and character>=65:            #ascii code for the uppercase letters
         letters+=1
     elif character<=122 and character>=97:         #ascii code for lowercase letters
         letters+=1
print(letters)
Cr4zySheep
  • 81
  • 4
  • okay so i changed the int to ord but now im getting the error ord() expected a character, but string of length 3 found. – user20232221 Oct 13 '22 at 16:46
  • 1
    @user20232221 that's because your code split the input into words, not characters as your variable naming implies. – Mark Ransom Oct 13 '22 at 17:18
0

Once you have a word, it's easy to remove punctuation and count characters:

from string import punctuation

letters += len(c for c in word if c not in punctuation)
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50