簡體   English   中英

使用文件而不是字典時的python for循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM