itsjube

Untitled

Nov 5th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2. import re
  3. import time
  4. import collections
  5.  
  6. # ---- Definitions ----#
  7. #Amount of documents
  8. amount_of_documents = 1000
  9.  
  10. #Directory of raw HTML documents
  11. directory_of_raw_documents = "raw_documents/"
  12.  
  13. #Directory of parsed documents
  14. directory_of_parsed_documents = "parsed_documents/"
  15.  
  16. #List of h2s to ignore
  17. ignore_list = ['See_also','Notes','References','Related_journals','Notes_and_references','External_links','Further_reading','Sources','Footnotes','Related_pages','Quotations','Other_websites']
  18.  
  19. #Punctuation list to remove
  20. punctuation_list = ['\'',':',',','...','(',')','.','?','!','"',';']
  21.  
  22. #File name list to remove
  23. file_name_remove_list = ['_','-',' '] + punctuation_list
  24.  
  25. #File name to map document ids to document titles
  26. mapping_file_name = "document_id_mapping.txt"
  27.  
  28. #File to find the index of file names and urls
  29. index_of_file_names_and_urls = open('index-task1.txt', 'r')
  30. # ---- Code ----#
  31.  
  32. #grabs document names from index-task1
  33. def grab_document_names_from_index():
  34.     position = 0
  35.     document_dict = collections.OrderedDict()
  36.     for lines in index_of_file_names_and_urls:
  37.         position = position + 1
  38.         file_url = lines.split(str(position) + " - https://en.wikipedia.org/wiki/")
  39.         file_url = file_url[1]
  40.         file_url = file_url.split()
  41.         file_url = file_url[0]
  42.         file_url = ''.join(c for c in file_url if c not in file_name_remove_list) + ".txt"
  43.         document_dict[file_url] = position
  44.     return document_dict
  45.  
  46.  
  47.  
  48.  
  49. def open_document():
  50.     list_of_document_titles = []
  51.     document_index = collections.OrderedDict()
  52.     document_index = grab_document_names_from_index()
  53.     position = 0
  54.     for entry in document_index:
  55.         position = position+1
  56.         with open(directory_of_raw_documents + str(document_index[entry]), "r") as document:
  57.             html = document.read()
  58.             soup = BeautifulSoup(html, "html.parser")
  59.             body = soup.find('div', id='bodyContent')
  60.  
  61.             print("Processing document " + "(" + str(position) + "/" + str(amount_of_documents) + ")")
  62.  
  63.             #Clear tables
  64.             for table in body.find_all('table'): table.clear()
  65.  
  66.             #clear content table
  67.             for div in body.find_all('div', {'id' : 'toc'}): div.decompose()
  68.  
  69.             #Grab content
  70.             results = ""
  71.             for item in body.find_all(['h2','h3','p','li']):
  72.                 try:
  73.                     if item.name != 'h2': #We are not in the h2, therefore, lets find the id of the previous h2
  74.                         parent_h2_id = item.find_previous_sibling('h2').find('span')['id']
  75.                     else:
  76.                         parent_h2_id = item.find('span')['id']#If we are in the h2, get the ID.
  77.                 except (AttributeError, TypeError) as e: #error where there is no previous h2
  78.                     parent_h2_id = None
  79.                 if parent_h2_id and parent_h2_id in ignore_list:
  80.                     continue
  81.                 else:
  82.                     results += item.get_text() + "\n"
  83.                     #results = results.replace("[edit]", "")
  84.             results = results.encode('utf-8') #encodes it to stop weird errors
  85.             results = re.sub('\[(.*?)\]','',results, flags=re.DOTALL) #removes [edit] and any citations
  86.             results = remove_punctuation(results) #removes punctuation
  87.             results = results.lower() #makes results lower
  88.  
  89.  
  90.             print("Saved to " + entry)
  91.             #saves the document
  92.             output_file = open(directory_of_parsed_documents + entry, 'w')
  93.             output_file.write(results)
  94.             output_file.close()
  95.  
  96. #removes punctuation from provided string
  97. #but preserves punctuation between digits (I am allowing ALL punctuation)
  98. def remove_punctuation(string):
  99.     results = ""
  100.     previous = ""
  101.     next = ""
  102.     for i, c in enumerate(string):
  103.         if (i > 0):
  104.             previous = string[i - 1]
  105.         if (i + 1 != len(string)):
  106.             next = string[i + 1]
  107.         if (not previous.isdigit() or not next.isdigit()):  # if the previous and the next one are not digits
  108.             if (c not in punctuation_list):
  109.                 results += c
  110.         else:
  111.             results += c
  112.     return results
  113.  
  114. open_document()
Add Comment
Please, Sign In to add comment