Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python3xlrd将xls转换为JSON_Python_Json_Python 3.x_Xls_Xlrd - Fatal编程技术网

使用python3xlrd将xls转换为JSON

使用python3xlrd将xls转换为JSON,python,json,python-3.x,xls,xlrd,Python,Json,Python 3.x,Xls,Xlrd,我必须使用python3和xlrd将xls文件直接转换为JSON文档 桌子是空的 它分为三个主要类别(出版物、内容、结论),其名称位于第一列(第一列为零),类别的行数可能会有所不同。每行在第3、5和7列上有三个关键值(指示符、评估、命题)。可能有空行或缺少值 我必须将该表转换为以下我直接编写的JSON数据,其中包含一个引用。这是有效的 { "EVALUATION": { "PUBLICATION": [ { "INDICATEUR": "Page

我必须使用python3和xlrd将xls文件直接转换为JSON文档

桌子是空的

它分为三个主要类别(出版物、内容、结论),其名称位于第一列(第一列为零),类别的行数可能会有所不同。每行在第3、5和7列上有三个关键值(指示符、评估、命题)。可能有空行或缺少值

我必须将该表转换为以下我直接编写的JSON数据,其中包含一个引用。这是有效的

{
"EVALUATION": {
    "PUBLICATION": [
        {
            "INDICATEUR": "Page de garde",
            "EVALUATION": "Inexistante ou non conforme",
            "PROPOSITION D'AMELIORATION": "Consulter l'example sur CANVAS"
        },
        {
            "INDICATEUR": "Page de garde",
            "EVALUATION": "Titre du TFE non conforme",
            "PROPOSITION D'AMELIORATION": "Utilisez le titre avalisé par le conseil des études"
        },
        {
            "INDICATEUR": "Orthographe et grammaire",
            "EVALUATION": "Nombreuses fautes",
            "PROPOSITION D'AMELIORATION": "Faire relire le document"
        },
        {
            "INDICATEUR": "Nombre de page",
            "EVALUATION": "Nombre de pages grandement différent à la norme",
            "PROPOSITION D'AMELIORATION": ""
        }
    ],
    "CONTENU": [
        {
            "INDICATEUR": "Développement du sujet",
            "EVALUATION": "Présentation de l'entreprise",
            "PROPOSITION D'AMELIORATION": ""
        },
        {
            "INDICATEUR": "Développement du sujet",
            "EVALUATION": "Plan de localisation inutile",
            "PROPOSITION D'AMELIORATION": "Supprimer le plan de localisation"
        },
        {
            "INDICATEUR": "Figures et capture d'écran",
            "EVALUATION": "Captures d'écran excessives",
            "PROPOSITION D'AMELIORATION": "Pour chaque figure et capture d'écran se poser la question 'Qu'est-ce que cela apporte à mon sujet ?'"
        },
        {
            "INDICATEUR": "Figures et capture d'écran",
            "EVALUATION": "Captures d'écran Inutiles",
            "PROPOSITION D'AMELIORATION": "Pour chaque figure et capture d'écran se poser la question 'Qu'est-ce que cela apporte à mon sujet ?'"
        },
        {
            "INDICATEUR": "Figures et capture d'écran",
            "EVALUATION": "Captures d'écran illisibles",
            "PROPOSITION D'AMELIORATION": "Pour chaque figure et capture d'écran se poser la question 'Qu'est-ce que cela apporte à mon sujet ?'"
        },
        {
            "INDICATEUR": "Conclusion",
            "EVALUATION": "Conclusion inexistante",
            "PROPOSITION D'AMELIORATION": ""
        },
        {
            "INDICATEUR": "Bibliographie",
            "EVALUATION": "Inexistante",
            "PROPOSITION D'AMELIORATION": ""
        },
        {
            "INDICATEUR": "Bibliographie",
            "EVALUATION": "Non normalisée",
            "PROPOSITION D'AMELIORATION": "Ecrire la bibliographie selon la norme APA"
        }
    ],
    "CONCLUSION": [
        {
            "INDICATEUR": "",
            "EVALUATION": "Grave manquement sur le plan de la présentation",
            "PROPOSITION D'AMELIORATION": "Lire le document 'Conseil de publication' disponible sur CANVAS"
        },
        {
            "INDICATEUR": "",
            "EVALUATION": "Risque de refus du document par le conseil des études",
            "PROPOSITION D'AMELIORATION": ""
        }
    ]
}
}

我的意图是通过行循环,检查行[1]以识别类别,并通过子循环将数据作为字典按类别添加到列表中

以下是我目前的代码:

import xlrd
file = '/home/eh/Documents/Base de Programmation/Feedback/EvaluationEI.xls'
wb = xlrd.open_workbook(file)
sheet = wb.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]


def readRows():
    for rownum in range(2,sheet.nrows):
        rows = sheet.row_values(rownum)
        indicateur = rows[3]
        evaluation = rows[5]
        amelioration = rows[7]
        publication = []
        contenu = []
        conclusion = []

        if rows[1] == "PUBLICATION":

            if rows[3] == '' and rows[5] == '' and rows[7] == '':
                continue
            else:
                publication.append("INDICATEUR : " + indicateur , "EVALUATION : " + evaluation , "PROPOSITION D'AMELIORATION : " + amelioration)

        if rows[1] == "CONTENU":

            if rows[3] == '' and rows[5] == '' and rows[7] == '':
                continue
            else:
                contenu.append("INDICATEUR : " + indicateur , "EVALUATION : " + evaluation  , "PROPOSITION D'AMELIORATION : " + amelioration)

        if rows[1] == "CONCLUSION":

            if rows[3] == '' and rows[5] == '' and rows[7] == '':
                continue
            else:
                conclusion.append("INDICATEUR : " + indicateur , "EVALUATION : " + evaluation , "PROPOSITION D'AMELIORATION : " + amelioration)

    print (publication)
    print (contenu)
    print (conclusion)




readRows()
我很难弄清楚如何子循环以获得正确的行数,从而按类别分隔数据

欢迎任何帮助


提前谢谢你

熊猫不是一种选择吗?将添加为评论,但没有代表

从文件


使用
json
包和
OrderedDict
(保留键顺序),我认为这达到了您的期望,我做了一些修改,因此我们没有构建字符串文本,而是构建一个
dict
,其中包含可以使用
json.dumps
转换的数据

正如Ron在上面提到的,您之前的尝试是跳过
行[1]
不等于三个键值之一的行

这应该读取最后一个非空键后面的每一行:

def readRows(file, s_index=0):
    """
    file:    path to xls file
    s_index: sheet_index for the xls file
    returns a dict of OrderedDict of list of OrderedDict which can be parsed to JSON
    """
    d = {"EVALUATION" : OrderedDict()}  # this will be the main dict for our JSON object
    wb = xlrd.open_workbook(file)  
    sheet = wb.sheet_by_index(s_index)
    # getting the data from the worksheet
    data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
    # fill the dict with data:
    for _,row in enumerate(data[3:]):
        if row[1]:  # if there's a value, then this is a new categorie element
            categorie = row[1]
            d["EVALUATION"][categorie] = []
        if categorie:  
            i,e,a = row[3::2][:3] 
            if i or e or a:  # as long as there's any data in this row, we write the child element
                val = OrderedDict([("INDICATEUR", i),("EVALUATION", e),("PROPOSITION D'AMELIORATION", a)])
                d["EVALUATION"][categorie].append(val)
    return d
这将返回一个
dict
,可以轻松解析为json。一些输出的屏幕截图:

:


注意:在Python3中,我认为您不需要
io。打开

看起来好像您想在找到发布行之后查找发布,但是您的代码只查看与发布相同的行(第3、5、7列),这些行是空的。rows[]列表实际上包含行的列的值。这将导致触发“continue”语句。您需要做的是让它搜索出版物行下方的行,以查看第3、5、7列是否包含有用的信息。谢谢您的帮助。Pandas看起来很有趣,但我这里的问题是xls文件的结构,它不是一个定向良好的表。也许如果我能用pandas清理并重新排列xls文件,我会找到一个解决方案。
def readRows(file, s_index=0):
    """
    file:    path to xls file
    s_index: sheet_index for the xls file
    returns a dict of OrderedDict of list of OrderedDict which can be parsed to JSON
    """
    d = {"EVALUATION" : OrderedDict()}  # this will be the main dict for our JSON object
    wb = xlrd.open_workbook(file)  
    sheet = wb.sheet_by_index(s_index)
    # getting the data from the worksheet
    data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
    # fill the dict with data:
    for _,row in enumerate(data[3:]):
        if row[1]:  # if there's a value, then this is a new categorie element
            categorie = row[1]
            d["EVALUATION"][categorie] = []
        if categorie:  
            i,e,a = row[3::2][:3] 
            if i or e or a:  # as long as there's any data in this row, we write the child element
                val = OrderedDict([("INDICATEUR", i),("EVALUATION", e),("PROPOSITION D'AMELIORATION", a)])
                d["EVALUATION"][categorie].append(val)
    return d
import io  # for python 2
d = readRows(file,0)
with io.open('c:\debug\output.json','w',encoding='utf8') as out:
    out.write(json.dumps(d,indent=2,ensure_ascii=False))