[英]python for loop when using file instead of dictionary
我使用自己的文件而不是Python字典,但是当我对该文件应用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
您正在导入json
模块,但没有使用它!
您可以使用json.load将打开的文件中的JSON数据加载到Python dict
,也可以将文件读取为字符串,然后使用json.loads将数据加载到dict
。
例如,
ofile = open("sai.json","r")
data = json.load(ofile)
ofile.close()
甚至更好
with open("sai.json", "r") as ifile:
data = json.load(ofile)
或者,使用json.loads
:
with open("sai.json", "r") as ifile:
dataset=ofile.read()
data = json.loads(dataset)
然后您可以使用data['text']
访问data
的内容,并
data['category']
,假设字典具有这些键。
您遇到错误,因为dataset
是字符串,所以
for n in dataset:
nTrainer.train(n['text'], n['category'])
逐个字符地遍历该字符串,将每个字符放入一个元素字符串中。 字符串只能用整数索引,不能用其他字符串索引,但是索引到一个元素字符串中的索引并不多,因为如果s
是一个元素字符串,那么s[0]
与s
内容相同
这是您放入评论中的数据。 我以为您的数据是包装在字典中的列表,但是可以将纯列表作为JSON对象是可以的。
FWIW,我使用print json.dumps(dataset, indent=4)
进行格式化。 请注意,文件中的最后一个}
后没有逗号:在Python中是可以的,但在JSON中是错误。
sai.json
[
{
"category": "NO",
"text": "hello everyone"
},
{
"category": "YES",
"text": "dont use words like jerk"
},
{
"category": "NO",
"text": "what the hell."
},
{
"category": "yes",
"text": "you jerk"
}
]
现在,如果我们使用json.load
读取它,您的代码应该可以正常工作。 但是这是一个仅演示内容的简单演示:
with open("sai.json", "r") as f:
dataset = json.load(f)
for n in dataset:
print "text: '%s', category: '%s'" % (n['text'], n['category'])
产量
text: 'hello everyone', category: 'NO'
text: 'dont use words like jerk', category: 'YES'
text: 'what the hell.', category: 'NO'
text: 'you jerk', category: 'yes'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.