我使用的,而不是一個Python字典我自己的文件時,但是當我在該文件上應用for
環路我收到此錯誤:蟒蛇for循環使用的文件,而不是字典
TypeError: string indices must be integers, not str
我的代碼在下面給出其中「sai.json」是包含字典的文件。
import json
from naiveBayesClassifier import tokenizer
from naiveBayesClassifier.trainer import Trainer
from naiveBayesClassifier.classifier import Classifier
nTrainer = Trainer(tokenizer)
ofile = open("sai.json","r")
dataset=ofile.read()
print dataset
for n in dataset:
nTrainer.train(n['text'], n['category'])
nClassifier = Classifier(nTrainer.data, tokenizer)
unknownInstance = "Even if I eat too much, is not it possible to lose some weight"
classification = nClassifier.classify(unknownInstance)
print classification
'N'是一個字符串,而不是一本字典。請做一些關於如何解析json的研究。使用'json'模塊 – Pynchia