文本如下:
#日期 流水号 被浏览页面URL 第×页 访问者IP 访问时间 是否入口 操作系统 浏览器 语言 时区 屏幕分辨率 屏幕色彩位数 省份 城市 接入商 上网场所 是否安装ALEXA
2014-7-17 11452775496 http://www.imaibo.net/space/178120 1 59.41.23.101 2014-7-17 13:38:14 0 Windows XP Chrome 21.0.8
2014-7-17 11452775466 http://www.imaibo.net/space/24649 3 211.143.83.60 2014-7-17 13:38:13 0
2014-7-17 11452775362 http://www.imaibo.net/live/216945 4 119.130.98.225 2014-7-17 13:38:12 0
2014-7-17 11452775357 http://www.imaibo.net/space/170907 6 58.50.218.120 2014-7-17 13:38:12 0
2014-7-17 11452775291 http://www.imaibo.net/space/113374 1 14.158.204.146 2014-7-17 13:38:11 1 Windows XP Chrome 21.0.1180 zh-cn 8 1360×768 32 广东 广东省 电信 0 14 9
。。。
思路:
1.将每一个field对应的在BSON文档中的key先存储到一个列表中,如:
keyarray = ["date","swiftnum","url","page","ip","atime","is_inpoint","system","browser","locale","timezone",
"screen","colornum","province","city","aprovider","netcase","isalexa","ipheader","count","keyword","domain","incomeurl"]
2.从文件中读取文本数据,用for in循环遍历每一条文本记录,使用re模块的split方法,利用定义的pattern=r‘ *’ 将每一行文本记录分解为的field组成的list
3.用一个for in循环对每一条记录的list遍历,将list中的值作为value,依次取出keyarray中的元素作为key,组成每一条文本记录对应的BSON文档,这样就实现了文本记录转换为BSON文档。
4.为了防止重复插入相同的记录,设计一个算法实现如下:
a.找到可以唯一标识每条记录的key-value,(本例:swiftnum)
b.在每次将每一条记录的BSON文档插入MongoDB中的同时,将对应的swiftnum的值写到一个文件swiftnums.txt中。
c.在每次插入记录BSON文档之前先做判断,是否要插入的BSON文档的swiftnum的值not in在swiftnums.txt中,若是的话,则插入,反之则跳过。
代码如下:
import os,glob
import re,pymongo
#-----连接MongoDB-----
conn = pymongo.Connection("localhost",27017)
db = conn.flowcounter
flowlist = db.flowcollection
#要存储的文本
file = open("test.txt","r")
#用于存储每一条记录的swiftnum值,以防止重复插入
swiftnums = open("swiftnums.txt","r+")
#每条记录转成BSON文档时,每个域对应的key
keyarray = ["date","swiftnum","url","page","ip","atime","is_inpoint","system","browser","locale","timezone",
"screen","colornum","province","city","aprovider","netcase","isalexa","ipheader","count","keyword","domain","incomeurl"]
#分解文本记录用到的正则
pattern = r' *'
#包含数据库中已有的记录的swiftnum的list
swiftnum_list = swiftnums.read().split(",")
for line in file.readlines()[1:]:
i = 0
data = {}
li_list = re.split(pattern,line) #分解记录为list
for field in li_list:
data[keyarray[i]]=field #将记录转为BSON文档
i +=1
if data['swiftnum'] not in swiftnum_list: #判断是否重复
flowlist.insert(data)
swiftnums.write(data['swiftnum']+",") #记录已有记录
swiftnums.close()