简体   繁体   中英

TypeError: list indices must be integers or slices, not string

so i got this error while trying to run the following code , i thought first that it might be that i didn't correctly convert the string to the list , but it seems to me that's it's correct or i'm i wrong ? , thanks.

here's on what i'm trying to run the Code:

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L194', 'L195', 'L196', 'L197']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L198', 'L199']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L200', 'L201', 'L202', 'L203']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L204', 'L205', 'L206']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L207', 'L208']

conversations_fields = ['Character_one_ID' , 'Character_two_ID' , 'Movie_ID' , 'utteranceIDs']
conversations = []
with open("./cornell movie-dialogs corpus/movie_conversations.txt", 'r', encoding='iso-8859-1') as f:
    for line in f:
        values = line.split(" +++$+++ ")
        # Extract fields
        convObj = {}
        for i, field in enumerate(conversations_fields):
            convObj[field] = values[i]
        # Convert string to list (convObj["utteranceIDs"] == "['L598485', 'L598486', ...]")
        lineIds = eval(convObj["utteranceIDs"])
        # Reassemble lines
        convObj['lines'] = []
        for lineId in lineIds:
            convObj['lines'].append(lines[lineId]
        conversations.append(convObj)

TypeError Traceback (most recent call last)

 <ipython-input-34-d7002161f69c> in <module>()

 13         convObj['lines'] = []
 14         for lineId in lineIds:
 ---> 15             convObj['lines'].append(lines[lineId])
 16         conversations.append(convObj)

TypeError: list indices must be integers or slices, not str

lineIds = convObj['utteranceIDs'] is filled with the eval of "['L194', 'L195', 'L196', 'L197']" - see Why is using 'eval' a bad practice? :

  lineIds = eval(convObj["utteranceIDs"]) 

lineIds is a list of strings, lineID is also a string ( "L194" then "L195" etc...) - you can not use it to index into lines :

  for lineId in lineIds: convObj['lines'].append(lines[lineId]) # you also missed a ) here 

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