所以我在尝试运行以下代码时遇到此错误,我首先想到这可能是我没有正确将字符串转换为列表,但是在我看来这是正确的,或者我错了? ,谢谢。
这是我正在尝试运行代码的内容:
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跟踪(最近一次通话最近)
<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:列表索引必须是整数或切片,而不是str
答案 0 :(得分:2)
Int: 1
Remainder: 0.753242342
Rounded remainder: 0.5
Result: 1.5
用lineIds = convObj['utteranceIDs']
的{{1}}填充-请参见Why is using 'eval' a bad practice?:
eval
"['L194', 'L195', 'L196', 'L197']"
是字符串列表, lineIds = eval(convObj["utteranceIDs"])
也是 字符串(lineIds
然后是lineID
等)-您可以不使用它索引到"L194"
:
"L195"