gpt4 book ai didi

使用文件而不是字典时的python for循环

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:02 25 4
gpt4 key购买 nike

我使用自己的文件而不是 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'

关于使用文件而不是字典时的python for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33580088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com