[英]Python 'builtin_function_or_method' object is not iterable error
i created this program which will replace a sentence with the words in its position and saves them as a separate file. 我创建了此程序,该程序将用其位置的单词替换一个句子并将其保存为单独的文件。 However when i run it i get this error: Traceback (most recent call last): File , line 12, in Positions = list2.index(word) 但是,当我运行它时,出现以下错误:追溯(最近一次调用最近):Files,第12行,位置= list2.index(word)
here is the code: 这是代码:
UserSentence = input("enter sentence:").lower()
words = UserSentence
words = words.split()
number = 0
list1 = []
list2 = " "
for Position in words:
if Position not in list1:
list1.append(Position)
for word in words:
Positions = list2.index(word)
list2+=str(Positions+int("1"))
list2 +=("")
list1str += ";".join(list1)
file = open ("myfile.txt","w")
file.write(sentence)
file.write(list1str)
file.write(list2)
file = open ("myfile.txt", "r")
print (file.read())
file.close()
could someone explain me what mistake i made in my code? 有人可以解释我在代码中犯了什么错误吗?
UserSentence = input("enter sentence:").lower()
words = UserSentence
words = words.split() # actually call the function
Without using the parentheses, you are actually assigning the method .split
to the variable words
, then trying to iterate over it, giving you the error. 不使用括号,实际上是将.split
方法分配给变量words
,然后尝试对其进行迭代,从而给您带来错误。
You set words = words.split
, but you aren't actually calling the method, so instead you are trying to iterate over the reference to that function. 您设置words = words.split
,但实际上并没有调用该方法,因此您尝试遍历对该函数的引用。 Call the method instead with words = words.split()
改为使用words = words.split()
调用该方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.