我正在閱讀列表項目,加入列表中的項目以對其執行一些操作
json_data=open("example2__test.json").read()
test_action = json.loads(json_data)
for input_action in test_action:
print " ".join(input_action["logs"])
這工作正常。
現在我test_action
在其他一些 for 循環中使用
for input_action in test_action:
for record in data:
res = {}
item = re.sub('[^a-zA-Z0-9]', ' '," ".join(record["logs"]))
input_action = re.sub('[^a-zA-Z0-9]',' '," ".join(input_action["logs"]))
item = stopwords_removal(item)
我收到此錯誤
TypeError Traceback (most recent call last)
<ipython-input-29-d42d327f3292> in <module>()
11 # temp = " ".join(input_action["logs"])
12
---> 13 input_action = re.sub('[^a-zA-Z0-9]',' '," ".join(input_action["logs"]))
14 item = stopwords_removal(item)
TypeError: string indices must be integers
為什麼它會出現此錯誤,我無法理解。此處" ".join(record["logs"])
也執行相同的操作,但不會出現此錯誤。
for input_action in test_action:
for record in data:
res = {}
item = re.sub('[^a-zA-Z0-9]', ' '," ".join(record["logs"]))
#problem in below line
input_action = re.sub('[^a-zA-Z0-9]',' '," ".join(input_action["logs"]))
item = stopwords_removal(item)
問題是您已重新分配 input_action 作為re.sub('[^a-zA-Z0-9]',' '," ".join(input_action["logs"]))
. 在“data”循環的第一遍中,input_action 可能是一個字典。但是在您的第二遍中,它絕對是一個字符串,因此input_action["logs"]
會引發該錯誤。問題發生在內部循環的第二次迭代中,而不是第一次。
編輯:底線,您input_action
在內循環的每次傳遞中都在改變變量,如果它運行的次數超過 1,它將失敗。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句