[英]Why does my code give the TypeError: TypeError: 'int' object has no attribute '__getitem__'?
I am making a script on Python that you give a string, and it will find the count of the letters in the string, input it into a list, and add up that list.我正在 Python 上制作一个脚本,你给出一个字符串,它会找到字符串中字母的数量,将其输入到一个列表中,然后将该列表相加。 My script runner keeps giving this error:
我的脚本运行器不断给出这个错误:
Traceback (most recent call last):
File "Untitled.py", line 9, in <module>
countersplit = len(tosplit[counter])
TypeError: 'int' object has no attribute '__getitem__'
My code is as follows:我的代码如下:
userin = raw_input("Enter sentence: ")
split = userin.split()
tosplit = len(split)
print(tosplit)
counter = 0
countersplit = 0
while counter < tosplit:
countersplit = len(tosplit[counter])
wordcount = [countersplit]
print(wordcount)
print(countersplit)
counter = counter + 1
What can I do you fix this problem?我能做些什么来解决这个问题?
Maybe this is what you're trying to achieve.也许这就是您想要实现的目标。
userin = raw_input("Enter sentence: ")
split = userin.split()
word_counts = list()
total_letters = 0
for i in split:
word_count = len(split)
print(word_count)
word_counts.append(word_count)
total_letters += word_count
print(total_letters)
You are getting this error because of "tosplit[counter]".由于“tosplit [counter]”,您会收到此错误。 From your definition "tosplit" is an integer that is equal to the length of "split".
根据您的定义,“tosplit”是一个 integer,它等于“split”的长度。 Hence you cannot have and index as in tosplit[counter].
因此,您不能像在 tosplit[counter] 中那样拥有和索引。 For the solution to your problem, is this what you need?
为了解决您的问题,这是您需要的吗?
from collections import defaultdict
import string
letters = list(string.ascii_lowercase)
string = input('Enter a String : ')
string = string.lower()
d = defaultdict(int)
for i in string:
if i in letters:
d[i]+=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.