Why does my code give the TypeError: TypeError: 'int' object has no attribute '__getitem__'?
Why does my code give the TypeError: TypeError: 'int' object has no attribute '__getitem__'?
我正在 Python 上编写一个脚本,你给一个字符串,它会找到字符串中字母的计数,将其输入到一个列表中,然后将该列表相加。我的脚本运行程序不断出现此错误:
Traceback (most recent call last):
File "Untitled.py", line 9, in <module>
countersplit = len(tosplit[counter])
TypeError: 'int' object has no attribute '__getitem__'
我的代码如下:
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
你能解决这个问题吗?
也许这就是您要实现的目标。
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)
您收到此错误是因为 "tosplit[counter]"。根据您的定义 "tosplit" 是一个等于 "split" 长度的整数。因此,您不能像在 tosplit[counter] 中那样拥有和索引。为了解决您的问题,这是您需要的吗?
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
我正在 Python 上编写一个脚本,你给一个字符串,它会找到字符串中字母的计数,将其输入到一个列表中,然后将该列表相加。我的脚本运行程序不断出现此错误:
Traceback (most recent call last):
File "Untitled.py", line 9, in <module>
countersplit = len(tosplit[counter])
TypeError: 'int' object has no attribute '__getitem__'
我的代码如下:
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
你能解决这个问题吗?
也许这就是您要实现的目标。
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)
您收到此错误是因为 "tosplit[counter]"。根据您的定义 "tosplit" 是一个等于 "split" 长度的整数。因此,您不能像在 tosplit[counter] 中那样拥有和索引。为了解决您的问题,这是您需要的吗?
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