python编程之制作省市县名称字典
文章目录
在失踪儿童信息保存在本地之后,有一个字段是失踪地点,字段内容通常比较详细,具体到了失踪的街道或者村,我打算通过某种方法将失踪地点中的省、市、县/区三级地址提取出来。
确定分词技术
知道要干什么之后,那就将这个“某种方法”确定下来,根据以往的知识积累,利用分词的原理来做,可能会更简单。这次就不用php来写了,换成python,在我的电脑上已经安装了python的开发环境,在python下使用的分词组件,搜索了一下,jieba用的比较多,而且调用也非常的容易。
准备字典文件
为了更加准确的将失踪地址中的省、市、县三级单位提取出来,最好能够直接以省、市、县、区的名称为字典,这样通过分词99%以上的词都能准确的切分出来。
在网上搜索发现,根据最新的国家统计区位码之作的现成的字典文件,并没有。但是有同学之前开发过爬虫将这些区位关系存在了mysql数据库,并且在网上有他放出来的sql备份文件,下载下来恢复到数据库中即可。
这个文件包含70多万行数据,在导入数据库的过程大约花了十来分钟。数据表如下:
因此,还需要将数据表中province_name,city_name,county_name提取出来即可,逐行存入文件就成为可以使用的字典文件。
import pymysql
class AnManMysql:
phost = '127.0.0.1'
pyuer = 'root'
password = '123456'
database = 'anman_org'
def pyMyConnection(phost,pyuser,password,database):
db = pymysql.connect(phost,pyuser,password,database,charset="utf8")
# cursor = db.cursor()
return db
# 导出省市县镇村字典
def getDict(db):
cursor = db.cursor()
cursor.execute("select distinct province_name from j_position")
data = cursor.fetchall()
# 打开字典文件my.dict
fo = open("my.dict","w+")
for da in data:
print(da[0])
fo.seek(0,2)
fo.write(da[0]+"\n")
print(len(data))
cursor.execute("select distinct city_name from j_position")
data = cursor.fetchall()
for da in data:
print(da[0])
fo.seek(0, 2)
fo.write(da[0] + "\n")
print(len(data))
cursor.execute("select distinct county_name from j_position")
data = cursor.fetchall()
for da in data:
print(da[0])
fo.seek(0, 2)
fo.write(da[0] + "\n")
print(len(data))
cursor.execute("select distinct town_name from j_position")
data = cursor.fetchall()
for da in data:
print(da[0])
fo.seek(0, 2)
fo.write(da[0] + "\n")
print(len(data))
# cursor.execute("select distinct village_name,village_id from j_position")
# data = cursor.fetchall()
# for da in data:
# print(da[0])
# print(da[1])
# fo.seek(0, 2)
# fo.write(da[0] + "\n")
# print(len(data))
fo.close()
在python里新建一个类,增加一个方法,打开一个字典文件,逐个从数据库中distinct字段,然后逐行追加到字典文件中。
cursor = AnManMysql.pyMyConnection(AnManMysql.phost,AnManMysql.pyuer,AnManMysql.password,AnManMysql.database)
AnManMysql.getDict(cursor)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论