Python 每日一練 6

2022-06-21 04:54:13 字數 2679 閱讀 4212

而今天的另乙個主角xml又是乙個什麼呢?

xml指的是可擴充套件標記語言extensible markup language,和json類似也是用於儲存和傳輸資料,還可以用作配置檔案。類似於html超文字標記語言,但是html所有的標籤都是預定義的,而xml的標籤可以隨便定義。

有關python解析xml可以看一下這篇文章:

def getxlsdata(filepath):

file = xlrd.open_workbook(filepath)#開啟乙個xls檔案,若檔名含有中文,則filepath前要加乙個r,寫作r'filepath'

sheet = file.sheet_by_index(0)

#通過索引來獲取工作表,也可以選擇用名稱來獲取,則使用sheet_by_name(sheet_name)

content = {}

for i in range(sheet.nrows):#sheet.nrows用於獲取有效的行數,即寫有資料的行

content.setdefault(sheet.row_values(i)[0],sheet.row_values(i)[1:])

#將xls檔案中資料存入字典,第乙個表示序號的當作key,後面的元素當作value

return(content)

def writexml(content):

xmlfile = minidom.document()#建立xml檔案

root = xmlfile.createelement('root')#建立節點

students = xmlfile.createelement('students')#建立節點

comment = xmlfile.createcomment('學生資訊表 "id" : [名字, 數學, 語文, 英文]')

xmlcontent = xmlfile.createtextnode(str(content)) #建立文字節點

with open('student.xml','wb') as f:

f.write(xmlfile.toprettyxml(newl='\n',encoding = 'utf-8')) #寫入檔案

# -*- coding:utf-8 -*-

# author:konmu

'''將 第 0014 題中的 student.xls 檔案中的內容寫到 student.xml 檔案中,如

下所示:

<?xml version="1.0" encoding="utf-8"?>

'''import xlrd

import xml.dom.minidom as minidom

def getxlsdata(filepath):

file = xlrd.open_workbook(filepath)#開啟乙個xls檔案,若檔名含有中文,則filepath前要加乙個r,寫作r'filepath'

sheet = file.sheet_by_index(0)

#通過索引來獲取工作表,也可以選擇用名稱來獲取,則使用sheet_by_name(sheet_name)

content = {}

for i in range(sheet.nrows):#sheet.nrows用於獲取有效的行數,即寫有資料的行

content.setdefault(sheet.row_values(i)[0],sheet.row_values(i)[1:])

#將xls檔案中資料存入字典,第乙個表示序號的當作key,後面的元素當作value

return(content)

def writexml(content):

xmlfile = minidom.document()#建立xml檔案

root = xmlfile.createelement('root')#建立節點

students = xmlfile.createelement('students')#建立節點

comment = xmlfile.createcomment('學生資訊表 "id" : [名字, 數學, 語文, 英文]')

xmlcontent = xmlfile.createtextnode(str(content)) #建立文字節點

with open('student.xml','wb') as f:

f.write(xmlfile.toprettyxml(newl='\n',encoding = 'utf-8')) #寫入檔案

if __name__ == "__main__":

filepath = "c:/users/konmu/desktop/students.xls"

content=getxlsdata(filepath)

writexml(content)

f=open('snew.xml','w')

xmlfile.writexml(f,indent = '\t',newl = '\n', addindent = '\t',encoding = 'utf-8')

f.close()

python每日一練

人生苦短,我用python 2018.6.5 有個目錄,裡面是你自己寫過的程式,統計一下你寫過多少行 包括空行和注釋,但是要分別列出來 coding utf 8 import re import glob defcodecolletion path filelist glob.glob path p...

Python每日一練

人生苦短,我用python 2018.6.13 最近事情有點多,有幾天沒寫了,正好最近需要統計一下各組排名,也就拿python代替手工了 各組給出其他組的排名,統計每個組最終的得分,第一名為0.5,第二名0.4,以此類推。coding utf 8 groups 3,2,5,4,6 1,3,5,6,4...

Python每日一練0002

如何序列化輸出元素包含字串元組的字串元組 好繞 舉個例子 zoo1 monkey elephant zoo2 python zoo1 將zoo2輸出為python,monkey,elephant容易想到使用join 函式,但join 函式要求元素必須都是字串型別,否則會丟擲typeerror錯誤 z...