Python 3.6.5统计字母时遇TypeError: 'int' object is not iterable如何修复?
Hey there, let's break down what's going wrong and fix your code step by step.
The Root Cause of the Error
That TypeError: 'int' object is not iterable is coming from this line:
for i in h:
You set h = len(line) which gives you an integer (the length of the current line). But for loops need an iterable object (like a string, list, or tuple) to loop through—you can't loop over a single integer, hence the error.
On top of that, your character check was off: if line == "a" or line == "A" was comparing the entire line to a single character, which would never be true. You need to check each individual character instead.
Corrected Code
Here's the fixed version that will count all 'a' and 'A' characters correctly:
x = 0 f = open('in_a.txt', encoding='utf-8') for line in f: # Loop through each character in the current line directly for char in line: if char == "a" or char == "A": x += 1 print("this document has %d A or a characters" % (x))
Key Changes Made
- Removed
h = len(line)and the invalidfor i in hloop—instead, we iterate directly over thelinestring (strings are iterable, so we can loop through each character one by one) - Changed
linetocharin the condition check, so we're verifying each single character instead of the whole line - Tweaked "documents" to "document" for grammatical accuracy
When you run this with your test text, it will output exactly what you expect: this document has 10 A or a characters.
内容的提问来源于stack exchange,提问作者Crazy coding kid

