我有这个代码,我正在尝试解压缩。首先,我已经压缩了所有工作的代码,但是当我解压缩它时会出现一个ValueError。
List.append(dic[int(bob)])
ValueError: invalid literal for int() with base 10: '1,2,3,4,5,6,7,8,9,'
这是代码......
def menu():
print("..........................................................")
para = input("Please enter a paragraph.")
print()
s = para.split() # splits sentence
another = [0] # will gradually hold all of the numbers repeated or not
index = [] # empty index
word_dictionary = [] # names word_dictionary variable
for count, i in enumerate(s): # has a count and an index for enumerating the split sentence
if s.count(i) < 2: # if it is repeated
another.append(max(another) + 1) # adds the other count to another
else: # if is has not been repeated
another.append(s.index(i) +1) # adds the index (i) to another
new = " " # this has been added because other wise the numbers would be 01234567891011121341513161718192320214
another.remove(0) # takes away the 0 so that it doesn't have a 0 at the start
for word in s: # for every word in the list
if word not in word_dictionary: # If it's not in word_dictionary
word_dictionary.append(word) # adds it to the dicitonary
else: # otherwise
s.remove(word) # it will remove the word
fo = open("indx.txt","w+") # opens file
for index in another: # for each i in another
index= str(index) # it will turn it into a string
fo.write(index) # adds the index to the file
fo.write(new) # adds a space
fo.close() # closes file
fo=open("words.txt", "w+") # names a file sentence
for word in word_dictionary:
fo.write(str(word )) # adds sentence to the file
fo.write(new)
fo.close() # closes file
menu()
index=open("indx.txt","r+").read()
dic=open("words.txt","r+").read()
index= index.split()
dic = dic.split()
Num=0
List=[]
while Num != len(index):
bob=index[Num]
List.append(dic[int(bob)])
Num+=1
print (List)
问题出现在第50行。使用'List.append(dic [int(bob)])'。 有没有办法让错误信息停止弹出,并输出上面输入的句子代码?
发生了最新的错误消息: List.append(DIC [INT(BOB)]) IndexError:列表索引超出范围
当我运行代码时,我输入“这是一个句子。这是另一个句子,用逗号。”
答案 0 :(得分:1)
问题是index= index.split()
默认情况下是在空格上拆分,并且如异常所示,您的数字由,
分隔。
没有看到index.txt
我无法确定它是否会修复所有索引,但对于OP中的问题,您可以通过指定要拆分的内容来修复它,即逗号:
index= index.split(',')
关于第二个问题,List.append(dic[int(bob)]) IndexError: list index out of range
有两个问题:
这可以通过以下方式解决:
List.append(dic[int(bob) - 1])
此外,你做的工作比你需要的多得多。这样:
fo = open("indx.txt","w+") # opens file
for index in another: # for each i in another
index= str(index) # it will turn it into a string
fo.write(index) # adds the index to the file
fo.write(new) # adds a space
fo.close() # closes file
相当于:
with open("indx.txt","w") as fo:
for index in another:
fo.write(str(index) + new)
和此:
Num=0
List=[]
while Num != len(index):
bob=index[Num]
List.append(dic[int(bob)])
Num+=1
相当于
List = []
for item in index:
List.append(dic[int(item)])
另外,请花点时间查看PEP-8并尝试遵循这些标准。您的代码很难阅读,因为它不遵循它们。我修改了你的评论格式,因此StackOverflow的解析器可以解析你的代码,但大多数只会增加混乱。