简体   繁体   English

TypeError:列表索引必须是整数或切片,而不是字符串

[英]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 +++ $ +++ ['L194','L195','L196','L197']

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

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

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

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L207', 'L208'] 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) TypeError跟踪(最近一次通话)

 <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 TypeError:列表索引必须是整数或切片,而不是str

lineIds = convObj['utteranceIDs'] is filled with the eval of "['L194', 'L195', 'L196', 'L197']" - see Why is using 'eval' a bad practice? lineIds = convObj['utteranceIDs']"['L194', 'L195', 'L196', 'L197']"eval值填充-请参阅为什么使用“评估”是一种不好的做法? :

  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 : lineIds是一个字符串列表, lineID 也是一个字符串( "L194"然后"L195"等...)-您不能使用它来索引lines

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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