itsjube

Untitled

Nov 5th, 2016
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.19 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from bs4 import BeautifulSoup
  3. import re
  4. import time
  5. import collections
  6.  
  7. # ---- Definitions ----#
  8. #Amount of documents
  9. amount_of_documents = 1000
  10.  
  11. #Directory of raw HTML documents
  12. directory_of_raw_documents = "raw_documents/"
  13.  
  14. #Directory of parsed documents
  15. directory_of_parsed_documents = "parsed_documents/"
  16.  
  17. #Punctuation list to remove
  18. punctuation_list = ['\\','/',':',',','...','(',')','.','?','!','\"',';','\'','’']
  19.  
  20. #File name list to remove
  21. file_name_remove_list = ['_','-',' '] + punctuation_list
  22.  
  23. #File name to map document ids to document titles
  24. mapping_file_name = "document_id_mapping.txt"
  25.  
  26. #File to find the index of file names and urls
  27. index_of_file_names_and_urls = open('index-task1.txt', 'r')
  28. # ---- Code ----#
  29.  
  30. #grabs document names from index-task1
  31. def grab_document_names_from_index():
  32.     position = 0
  33.     document_dict = collections.OrderedDict()
  34.     for lines in index_of_file_names_and_urls:
  35.         position = position + 1
  36.         file_url = lines.split(str(position) + ".txt - https://en.wikipedia.org/wiki/")
  37.         file_url = file_url[1]
  38.         file_url = file_url.split()
  39.         file_url = file_url[0]
  40.         file_url = ''.join(c for c in file_url if c not in file_name_remove_list) + ".txt"
  41.         document_dict[file_url] = position
  42.     return document_dict
  43.  
  44.  
  45.  
  46.  
  47. def open_document():
  48.     list_of_document_titles = []
  49.     document_index = collections.OrderedDict()
  50.     document_index = grab_document_names_from_index()
  51.     position = 0
  52.     for entry in document_index:
  53.         position = position+1
  54.         with open(directory_of_raw_documents + str(document_index[entry]) + ".txt", "r", encoding='utf-8') as document:
  55.             html = document.read()
  56.             soup = BeautifulSoup(html, "html.parser")
  57.             body = soup.find('div', id='bodyContent')
  58.  
  59.             print("Processing document " + "(" + str(position) + "/" + str(amount_of_documents) + ")")
  60.  
  61.             #Remove tables
  62.             for table in body.find_all('table'): table.clear()
  63.  
  64.             #Remove content table
  65.             for div in body.find_all('div', {'id' : 'toc'}): div.decompose()
  66.  
  67.             #Remove hatnote
  68.             for class_item in body.find_all('div',{'class':'hatnote'}): class_item.decompose()
  69.  
  70.             #Remove images
  71.             for img in body.find_all('img'): img.decompose()
  72.  
  73.             #Remove references
  74.             for class_item in body.find_all('ol', {'class':'references'}): class_item.decompose()
  75.  
  76.             #Remove thumbs
  77.             for div in body.find_all('div', {'class':'thumb'}): div.decompose()
  78.  
  79.             #Remove navigations
  80.             for div in body.find_all('div', {'class': 'navbox'}): div.decompose()
  81.  
  82.             #Remove references by other names
  83.             for div in body.find_all('div', {'class': 'reflist'}): div.decompose()
  84.  
  85.             #Remove reference heading
  86.             for span in body.find_all('span',{'id': 'References'}): span.decompose()
  87.  
  88.             #Remove hidden div
  89.             for div in body.find_all('div',{'id': 'mw-hidden-catlinks'}): div.decompose()
  90.  
  91.             #Remove site hub
  92.             for div in body.find_all('div',{'id': 'siteSub'}): div.decompose()
  93.  
  94.             #Remove footer
  95.             for div in body.find_all('div', {'class': 'printfooter'}): div.decompose()
  96.  
  97.             #Remove jump-to-nav
  98.             for div in body.find_all('div', {'id': 'jump-to-nav'}): div.decompose()
  99.  
  100.             #Remove bottom navigation
  101.             for div in body.find_all('div', {'role':'navigation'}): div.decompose()
  102.  
  103.             #Remove normal catlinks
  104.             for div in body.find_all('div', {'id': 'mw-normal-catlinks'}): div.decompose()
  105.  
  106.             #remove
  107.  
  108.             #Grab content
  109.             results = ""
  110.             #for item in body.find_all(['h2','h3','p','li']):
  111.             #for item in body.find_all(['h2', 'h3', 'p', 'li']):
  112.                 #results += item.get_text() + " "
  113.                 #results = results.replace("[edit]", "")
  114.             results = body.get_text()
  115.             results = results.replace('\n',' ')
  116.             results = ' '.join(results.split())
  117.             results = re.sub('\[(.*?)\]','',results, flags=re.DOTALL) #removes [edit] and any citations
  118.             results = remove_punctuation(results) #removes punctuation
  119.             results = results.lower() #makes results lower
  120.  
  121.  
  122.             print("Saved to " + entry)
  123.             #saves the document
  124.             output_file = open(directory_of_parsed_documents + entry, 'w')
  125.             output_file.write(results)
  126.             output_file.close()
  127.  
  128. #removes punctuation from provided string
  129. #but preserves punctuation between digits (I am allowing ALL punctuation)
  130. def remove_punctuation(string):
  131.     results = ""
  132.     previous = ""
  133.     next = ""
  134.     for i, c in enumerate(string):
  135.         if (i > 0):
  136.             previous = string[i - 1]
  137.         if (i + 1 != len(string)):
  138.             next = string[i + 1]
  139.         if (not previous.isdigit() or not next.isdigit()):  # if the previous and the next one are not digits
  140.             if (c not in punctuation_list):
  141.                 results += c
  142.         else:
  143.             results += c
  144.     return results
  145.  
  146. open_document()
Add Comment
Please, Sign In to add comment