简体   繁体   中英

Python “list index out of range”

I am having a bit of trouble with the following code. I am translating a phrase from English to pig latin and seem to encounter the following problem despite the numerous workarounds I have tried

Traceback (most recent call last):
File "C:/Users/PMARINA/Documents/Python/YI_WordEnkryption.py/PM_PhraseEnkryption.py">    , line 37, in <module>
english = wordlist[wordcount]
IndexError: list index out of range

Code:

import string
import re
english = (input('English --> Pig Latin:  ')).lower()
overlist = re.sub("[^\w]", " ",  english).split()
overcounter = len(overlist) -1
counter = 0
count = 0
wordcount = 0
wordlist = []
vowels = ['a','e','i','o','u','y','A','E','I','O','U','Y']
counter = 0
vlist = []
clist = []
vlength = len(vowels) -1
while counter <=vlength:
        vlist.append(vowels[counter])
        counter +=1
consonants = string.ascii_letters
clength = len(consonants) -1
counter = 0
while counter <= clength:
    clist.append(consonants[counter])
    counter +=1
clist.remove('A')
clist.remove('E')
clist.remove('I')
clist.remove('O')
clist.remove('U')
clist.remove('Y')
clist.remove('a')
clist.remove('e')
clist.remove('i')
clist.remove('o')
clist.remove('u')
clist.remove('y')
while count<= overcounter:
        english = wordlist[wordcount]      # Line 37
        length = len(english) -1
        while counter <=length:
            enlist.append(english[counter])
            counter +=1
        if enlist[0] in vlist:
            enlist.append(enlist[0])
            enlist.append('way')
            enlist.remove(enlist[0])
        else:
            enlist.append(enlist[0])
            enlist.append('ay')
            enlist.remove(enlist[0])
        wordlist.append(''.join(enlist))

    wordcount +=1
    count +=1
    counter = 0
    overcounter+=1
print(wordlist)

The wordlist list is empty

What you are trying to do is equivalent to this:

>>> test = []
>>> test[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

on an unrelated note, you could shorten this code:

clist.remove('A')
clist.remove('E')
clist.remove('I')
clist.remove('O')
clist.remove('U')
clist.remove('Y')
clist.remove('a')
clist.remove('e')
clist.remove('i')
clist.remove('o')
clist.remove('u')
clist.remove('y')

to this:

for letter in vowels:
    clist.remove(letter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM