dir(…)可以用來查看該變量支持的方法
#csv
##1.打開csv文件
import csv
csvfile = open('data-txt','r')
##2.查看csv文件內容(不打印)
列表:csv.reader(csvfile)
字典:csv.DictReader(csvfile)
#JSON
##1.打開並查看json文件
json_data = open('../data/chp3/data-text.json').read()
*ps: 與csv不同,此處需添加 .read()
*
否則會報錯: TypeError: the JSON object must be str, not 'TextIOWrapper'
原因:json庫和csv處理數據的方式不同 json.loads()
只能接受str,而csv.reader()只能接受文件對象
##2.載入json文件
json.loads(json_data)
#xml
##1.導入xml數據
from xml.etree import ElementTree as et
tree = et.parse('../data/chp3/data-text.xml')
root = tree.getroot()#調用樹的根元素(XML節點)
data = root.find('Data')
all_data = []#list,用來存放record字典的內容
for oberservation in data:
record = {}#dictioary,用來保存每一個鍵值對
for item in oberservation:
lookup_str = list(item .attrib.keys())#將鍵值對這個數組傳給lookup_str
lookup_key = lookup_str[0]#將該鍵值對的第一個元素作爲新字典record的鍵rec_key
if lookup_key == 'Numeric':
rec_key = 'Numeric'#若爲數字,則將鍵名改爲Numeric(不處理的話鍵名是數字)
rec_value = item.attrib['Numeric']#將數字賦爲它的鍵值
else:
rec_key = item.attrib[lookup_key]
rec_value = item.attrib['Code']
record[rec_key] = rec_value#將每一個新的鍵值對添加到record字典中
all_data.append(record)#將字典添加到列表中
print(all_data)
如下圖,所有顯示的內容是一個all_data[]列表
PS:item.text只有在標籤內有內容纔有用,否則返回的數值均爲None
##2.find() 和 findall()
當我使用find()時,print的是所有元素,而使用findall()卻只print了一個元素,這是爲什麼呢?
data = root.find('Data')
# data = root.findall('Data')
print(list(data))
這是find()的運行結果
這是findall()的運行結果
這兩者不是反了嗎這樣?求指教
#Excel
下面的代碼是一步步進行的,只是因爲不想新建多個文件所以直接將每一步的上一步註釋掉了
PS: pprint
用於美化輸出的內容
讀取excel文件需要 import xlrd
,若是寫,則要 import xlwt
import xlrd
import pprint
book = xlrd.open_workbook('../data/chp4/SOWC 2014 Stat Tables_Table 9.xlsx')
# for sheet in book.sheets():
# print(sheet.name)
sheet = book.sheet_by_name('Table 9 ')
# print (dir(sheet))
# print(sheet.nrows)#303行
# 使用range函數將303轉換成一個列表,使用for遍歷(一行爲列表的一個元素)
# # 輸出單元格內容
# # 法1:使用for循環嵌套
# for i in range(sheet.nrows):
# # print(i)
# # print(sheet.row_values(i))#輸出每一行的值,空格內無數據則輸出爲`''`
# row = sheet.row_values(i)
# for cell in row:
# print(cell)
# 輸出單元格內容
# 法2:使用計數器
# count = 0
# for i in range(sheet.nrows):
# if count < 20:
# if i > 14:
# row = sheet.row_values(i)
# print(i, row)
# count += 1
# 創建字典,國家名爲鍵
# count = 0
# data = {}
# for i in range(sheet.nrows):
# if count < 20:
# if i > 14:
# row = sheet.row_values(i)
# country = row[1]
# data[country] = {}
# # print(i, row)
# count += 1
# print(data)
# 刪除與計數器相關的代碼
data = {}
# py3將xrange和range 合併爲range
for i in range(14,sheet.nrows):
row = sheet.row_values(i)
country = row[1]
data[country] = {
'child_labor':{
'total':[row[4],row[5]],
'male':[row[6],row[7]],
'female':[row[8],row[9]],
},
'child_marriage':{
'marriaged_by_15':[row[10],row[11]],
'married_by_18':[row[12],row[13]],
}
}
# 可以加判斷語句以退出for循環
# if country == 'Afghanistan':
# print('break')
# break
# else:
# print(country)
pprint.pprint(data['Albania'])