首页 > 编程语言 >Python XmlTool

Python XmlTool

时间:2024-08-11 22:17:02浏览次数:12  
标签:__ Python cursor sql print import data XmlTool

 XML To Xlsx

import xml.etree.ElementTree as ET
import re

import pandas as pd


def main():
    tree = ET.parse("in/strings.xml")
    root = tree.getroot()
    patternKey = re.compile(r"\: \'(.+?)\'")
    data_list = []
    for child in root:
        data = ["", ""]
        attrib = str(child.attrib)
        valueStr = child.text
        keyStr = patternKey.search(attrib).group(1)
        data[0] = keyStr
        data[1] = valueStr
        data_list.append(data)
    # 数据读出
    data = pd.DataFrame(data_list)
    # 保存为xls格式
    data.to_excel('dataZN.xls', encoding='utf-8')


class Bean:
    def __init__(self, key, value):
        self.key = key
        self.value = value


if __name__ == "__main__":
    main()

 

Xlsx To XML

import xlrd
import json
import pymysql


def main():
    # list = {'cs', 'de', 'en', 'es', 'fr', 'it', 'ja', 'ko', 'pl', 'pt', 'ru', 'uk', 'zh'}
    list = {'pl'}
    list = {'nl','sv'}
    returnData = {}
    db = pymysql.connect(host="localhost", user="root", password="root", db="oclean")
    cursor = db.cursor()
    for item in list:
        print("item = " + item)
        # 读取Excel文件
        data = xlrd.open_workbook('in/oclean_t_language_hl.xls')
        table = data.sheets()[0]
        # 读取excel第一行数据
        rowstag = table.row_values(0)
        nrows = table.nrows
        f = open("./out/string_" + item + ".xml", "w", encoding='utf8')
        f2 = open("./out/string_error_" + item + ".xml", "w", encoding='utf8')
        # f.write("<resources>\n")
        for i in range(1, nrows):
            # 将字段名和excel数据存储为字典形式,并转换为json格式
            returnData[i] = json.dumps(dict(zip(rowstag, table.row_values(i))))
            # 通过编解码还原数据
            returnData[i] = json.loads(returnData[i])
            valueStr = returnData[i][item]
            zh = returnData[i]["zh"]
            sql = "SELECT keyId FROM t_language where zh= '%s' " % zh
            cursor.execute(sql)
            results = cursor.fetchall()
            if len(results) == 0:
                # 没有匹配上
                print("results = " )
                f2.write("<string name='" + str(zh + "'>" + str(valueStr.strip() + "</string>\n")))
            for row in results:
                print(row)
                print("zh = " + zh)
                print("valueStr = " + valueStr)
                f.write("<string name='" + str(row[0] + "'>" + str(valueStr.strip() + "</string>\n")))
        f.close()
        f2.close()
    print("结束")


if __name__ == "__main__":
    main()

  XML To DB

import xml.etree.ElementTree as ET
import re
import pymysql
import os
from pymysql.converters import escape_string


def main():
    db = pymysql.connect(host="xx.xx.xx.xx", user="xxx", password="xxx", db="YourDbName")
    cursor = db.cursor(B
    path = 'D:\\Codes\\rc\\main\\res\\'
    sql = 'truncate table t_language'
    cursor.execute(sql)
    db.commit()
    for file_name in os.listdir(path):
        if "values-" not in file_name:
            continue
        if "night" in file_name:
            continue
        print(">>> " + file_name)
        item = str(file_name.replace('values-', '').replace('-', '_'))
        tree = ET.parse(path + file_name + "/strings.xml")
        root = tree.getroot()
        patternKey = re.compile(r"\: \'(.+?)\'")

        for child in root:
            attrib = str(child.attrib)
            valueStr = child.text
            keyStr = patternKey.search(attrib).group(1)
            # print("keyStr ='%s' " % keyStr)
            try:
                sql = "SELECT * FROM t_language WHERE keyId = '%s'" % keyStr
                cursor.execute(sql)
                results = cursor.fetchone()
                if results:
                    # print("更新数据" + keyStr)
                    sql = "UPDATE t_language SET %s = '%s' WHERE keyId ='%s'" % (item, escape_string(valueStr), keyStr)
                    # print(sql)
                    cursor.execute(sql)
                    db.commit()
                else:
                    # print("插入数据")
                    sql = "INSERT INTO t_language(keyId,%s) VALUES ('%s', '%s')" % (
                        item, keyStr, escape_string(valueStr))
                    # print(sql)
                    cursor.execute(sql)
                    db.commit()
            except Exception as e:
                print("出现如下异常'%s'" % e)
                return
                # 关闭数据库连接
    db.close()
    print("结束")


if __name__ == "__main__":
    main()

 

标签:__,Python,cursor,sql,print,import,data,XmlTool
From: https://www.cnblogs.com/loaderman/p/18353993

相关文章

  • Python 虚拟环境安装flask框架 Read timed out.
    cmd输入workonenv_name激活pipinstallflask  升级pip:python-mpipinstall--upgradepip-ihttp://pypi.douban.com/simple--trusted-hostpypi.douban.com下载包:以flask-sqlalchemy为例:方案一:pipinstallFlask方案二:pipinstallflask-sqlalchemy-ihttp:/......
  • python+opencv+selenium自动化登录邮箱并解决滑动验证的问题
    本文主要讲解基于Python、OpenCV和Selenium的自动化登录邮箱并解决滑动验证问题。在这个过程中,我们需要特别注意页面元素的准确定位以及文本框和验证码的frame嵌套问题。感兴趣的朋友们一起来学习吧,让我们一起探索解决这个挑战的方法。前言大家在进行自动化登录时可能都......
  • Python打包命令汇总
    1、pyinstaller打包环境安装:pipinstallpyinstaller 网络不好可以通过-i指定安装源:pipinstallpyinstaller-ihttps://pypi.tuna.tsinghua.edu.cn/simple/安装完成后通过:pyinstaller--version查看是否安装成功打包单个脚本:pyinstaller-F-w-ipython.icomain.py......
  • Python虚拟环境
    虚拟环境安装1:安装好Python环境https://python.p2hp.com/downloads/     双击打开后弹窗显示下图,注意此处是两张图,都看完再进行下一步,第一步点击选中第二张图的Add这个选框,第二步选择第一张图自定义路径存储Customize。  选择自定义路径后会弹出此界面,不用......
  • 大一新生初入Python第五天
    大一新生初入Python第五天前言:有天没更新就是因为学这个流程控制语句我感觉这玩意应该在前期算比较难一点的了我尽量根据自己的理解写好一点吧一.程序的三大执行流程程序的三大执行流程分别为:1.顺序执行2.选择执行3.循环执行1.顺序执行顺序执行也就是你......
  • 基于Python的大模型学习手册(入门级)
    前言大模型(全称为大语言模型,英文名称:LargeLanguageModel),这个2023年刷爆了互联网圈的“现象级明星”,几乎以前所未有的姿态,席卷了各行各业,世人一时为之惊叹。同时,也开辟了各大厂商投入AI研发的新赛道。乘着这波“西风”,国内大模型开启了雨后春笋般的神奇发育,简直是“一浪......
  • python 如何获取当前时间
    python如何获取当前系统的时间1、导入包import datetime2、获取当前的时间curr_time = datetime.datetime.now()# 2019-07-06 14:55:56.873893 <class 'datetime.datetime'>curr_time.year# 2019 <class 'int'>curr_time.month# 7 <class......
  • python 如何获取毫秒级系统时间
    python如何获取毫秒级系统时间?下面给大家举个例子:import timeimport datetimet = time.time()print (t)                #原始时间数据print (int(t))              #秒级时间戳print (int(round(t * 1000)))     #毫秒......
  • Python - sum()
     >>>bugs=["bug1","bug2"]>>>sum(bugs,[])Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>TypeError:canonlyconcatenatelist(not"str")tolist>&g......
  • pyqt5+win32+python联合在CAD绘图无法绘制
    1初始报错想法是:写好pyqt5的简单界面代码后,用一个信号槽连接到CAD绘制图形。出现了报错:显示“已成功连接到CAD”,说明连接没有问题,但是“在CAD中绘制线条时出错:(-2147352567,'发生意外。',(0,None,None,None,0,-2147024809),None)”。搜索后给出可能原因是:1-参......