简体   繁体   中英

Iterate through a list of lists with indexes

I have a list of lists in Python which looks like this:

onlyText3 = [['Here', 'is', 'some', 'text'], ['Here', 'is', 'some', 'more', 'text']]

I need to iterate through every element of that list to

  1. Check whether the word is contained in a dictionary
  2. If the word is not in the dictionary and if it is a compound word split it up + add the resulting words to the list
  3. Replace unknown words with the first suggestion the dictionary provides (splitter.split('word') returns a list)

Im working with Pyenchant and the word-compound-splitter.

This is my code:

import enchant
import splitter

dictionary = enchant.dict("en_US")

for a in range(len(onlyText3)-1):
     for b in range(len(onlyText3[a])-1):
         if dictionary.check(onlyText3[a][b]):
             pass
         elif splitter.split(onlyText3[a][b]):
             for c in range(len(splitter.split(onlyText3[a][b]))-1):
                 onlyText3[a].insert(b+c, splitter.split(onlyText3[a][b])[c])
         else:
             if dictionary.suggest(onlyText3[a][b]): 
                 onlyText3[a][b] = dictionary.suggest(onlyText3[a][b])[0]

However, this yields an Index-Error:

onlyText3[a].insert(b+c, splitter1.split(onlyText3[a][b])[c])
IndexError: list index out of range

Is there something I have not thought through? Is there maybe an easier way to do this? I could not think of any better way since I do need to access each element with its index because I need the index in order to insert the words resulting from splitting up the compound words.

insert doesn't extend the list for you automatically. Try doing onlyText3[a].extend([None] * (b + c - len(onlyText3[a]))) before the line that breaks.

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