Guest User

Wikipedia

a guest
Apr 21st, 2013
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.35 KB | None | 0 0
  1. import re,BeautifulSoup as bs,cPickle
  2.  
  3. def main():
  4.     ids = {}
  5.     pages = set([])
  6.     idcounter = 1
  7.    
  8.     f = open("wiki.xml",'rb')
  9.    
  10.     f.seek(0,2)
  11.     length = f.tell()
  12.     f.seek(0)
  13.    
  14.     s = ['']
  15.     links = {}
  16.    
  17.     finder = re.compile(r'\[\[(.*?)(\||\]\])')
  18.     stop = True
  19.     cachehit=0
  20.     total = 1
  21.     wrap = 0
  22.    
  23.     while stop:
  24.         while '</page>' not in s[-1]: #read until a whole page has been read
  25.             s.append(f.read(16384))
  26.             if s[-1] == '':
  27.                 stop = False
  28.                 del s[-1]
  29.                 break
  30.            
  31.         split = s[-1].split('</page>',1) #removes the contents of the next page
  32.         s[-1] = split[0]+'</page>'
  33.         if len(split)==1:
  34.             leftover = ''
  35.         else:
  36.             leftover = split[1]
  37.         s = ''.join(s)
  38.        
  39.         soup = bs.BeautifulSoup(s)
  40.        
  41.         s = [leftover]
  42.        
  43.         for page in soup.findAll('page'):
  44.             title = page.find('title').text
  45.            
  46.             if title not in pages:#add to the link-to-number dict
  47.                 pages.add(title)
  48.                 ids[title] = idcounter
  49.                 idcounter+=1
  50.            
  51.             dd = "Currently on "+str(title.encode('ascii',"ignore"))
  52.             if len(dd)<45:#stops the text from going on to the next one
  53.                 if total==0:
  54.                     total=1
  55.                 print dd+(' '*(55-len(dd)))+"Done %f"%(float(f.tell())/length)+'% '+"%f"%(cachehit/total)+'\r',
  56.                
  57.             links[ids[title]]=[]
  58.             text = (page.findAll('text')[0]).text
  59.            
  60.             wrap+=1
  61.             if wrap%1000==0: #stops this number from flickering too fast to be read
  62.                 yay = 0.0
  63.                 total=0.0
  64.                 wrap=0
  65.            
  66.             for link in finder.findall(text):
  67.                 if link[0] in pages:
  68.                     links[ids[title]].append(ids[link[0]])
  69.                     cachehit+=1
  70.                     total+=1
  71.                 else:                        
  72.                     pages.add(link[0])
  73.                     ids[link[0]]=idcounter
  74.                     idcounter+=1
  75.                     total+=1
  76.     cPickle.dump(links,open(r'links.l','wb'))
  77.     cPickle.dump(ids,open(r"links.id",'wb'))
  78.  
  79. if __name__=='__main__':
  80.     main()
Advertisement
Add Comment
Please, Sign In to add comment