1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
| """ 原代码只将数据解析到文本,且对重复字段没有进行处理 <article> <author>Mr.A</author> <author>Mr.B</author> </article> 此代码修正了上述不足,然后将解析后字段导入数据库 读取数据:dblp.xml 2.01G 导入Mysql:170万+ 导入表:visual_dataset.dblp 生成备份文件:insert.sql @author: Administrator """
from __future__ import print_function import xml.sax import sys import io import re import logging import traceback import pymysql.cursors sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') logging.basicConfig(level=logging.DEBUG, format='%(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='I:\\ABC000000000000\\Dblp\\simple\\app.log', filemode='w')
class MovieHandler( xml.sax.ContentHandler ): ''' res 类变量,记录解析后的字段值 ''' athr = [] ee = [] res='' sqlval='' def __init__(self): self.CurrentData = "" self.author = "" self.title = "" self.pages = "" self.year = "" self.volume = "" self.journal = "" self.number = "" self.url = "" self.ee = "" def startElement(self, tag, attributes):
self.CurrentData = tag if tag == "article": try:
if len(self.__class__.sqlval) : lt = re.sub(",$","",self.__class__.sqlval).split(",") lt2= sorted(set(lt),key=lt.index)
insert_mysql( ','.join(lt2),self.__class__.res, ','.join(self.__class__.athr), ','.join(self.__class__.ee) ) except: traceback.print_exc() self.__class__.res='' self.__class__.sqlval='' self.__class__.athr=[] self.__class__.ee=[] mdate = attributes["mdate"] key = attributes["key"] self.__class__.res += mdate + SYMBOL + key + SYMBOL self.__class__.sqlval += "article_mdate,article_key,"
def endElement(self, tag): if self.CurrentData == "author": self.__class__.sqlval += "author," if '$_author_$' not in self.__class__.res: self.__class__.res += "$_author_$" + SYMBOL self.__class__.athr.append(self.author) elif self.CurrentData == "title": self.__class__.sqlval += "title," self.__class__.res += self.title + SYMBOL elif self.CurrentData == "pages": self.__class__.sqlval += "pages," self.__class__.res += self.pages + SYMBOL elif self.CurrentData == "year": self.__class__.sqlval += "year," self.__class__.res += self.year + SYMBOL elif self.CurrentData == "volume": self.__class__.sqlval += "volume," self.__class__.res += self.volume + SYMBOL elif self.CurrentData == "journal": self.__class__.sqlval += "journal," self.__class__.res += self.journal + SYMBOL elif self.CurrentData == "number": self.__class__.sqlval += "number," self.__class__.res += self.number + SYMBOL elif self.CurrentData == "url": self.__class__.sqlval += "url," self.__class__.res += self.url + SYMBOL elif self.CurrentData == "ee": self.__class__.sqlval += "ee," if '$_ee_$' not in self.__class__.res: self.__class__.res += "$_ee_$" + SYMBOL self.__class__.ee.append(self.ee) self.CurrentData = ""
def characters(self, content): if self.CurrentData == "author": self.author = content.replace("'","`") elif self.CurrentData == "title": self.title = content.replace("'","`") elif self.CurrentData == "pages": self.pages = content.replace("'","`") elif self.CurrentData == "year": self.year = content.replace("'","`") elif self.CurrentData == "volume": self.volume = content.replace("'","`") elif self.CurrentData == "journal": self.journal = content.replace("'","`") elif self.CurrentData == "number": self.number = content.replace("'","`") elif self.CurrentData == "url": self.url = content.replace("'","`") elif self.CurrentData == "ee": self.ee = content.replace("'","`")
''' 独立方法:将解析出的字段导入Mysql ''' def insert_mysql(names,values,authors,ees): global count if count==100: sys.exit val = re.sub(",'$","",values) val = re.sub("#","&",val) val = val.replace("$_ee_$",re.sub(",",",",ees)) val = val.replace("$_author_$",re.sub(",",",",authors)) sql = '' if len(names) & len(names): try: with connection.cursor() as cursor: sql = "INSERT INTO `dblp` (" sql +=names sql +=" )VALUES ('" sql +=val sql +=" )" count += 1 print('parse items and inserted :'+str(count)) if sql is not None and sql != 'None': logging.info(sql+';') cursor.execute(sql) connection.commit() a = 1 except: logging.error(traceback.print_exc())
if ( __name__ == "__main__"): count = 0 SYMBOL = "','"
XMLFPATH = "I:\\ABC000000000000\\Dblp\\dblp.xml" parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 0) Handler = MovieHandler() parser.setContentHandler( Handler )
connection = pymysql.connect( host='localhost', user='root', password='123', db='visual_dataset', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) parser.parse(XMLFPATH) connection.close()
|