itsjube

Untitled

Nov 5th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.41 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from bs4 import BeautifulSoup
  4. import re
  5. import time
  6. import collections
  7.  
  8. # ---- Definitions ----#
  9. #Amount of documents
  10. amount_of_documents = 1000
  11.  
  12. #Directory of raw HTML documents
  13. directory_of_raw_documents = "raw_documents/"
  14.  
  15. #Directory of parsed documents
  16. directory_of_parsed_documents = "parsed_documents/"
  17.  
  18. #List of h2s to ignore
  19. ignore_list = ['Notes','References','Related_journals','Notes_and_references','External_links','Further_reading','Sources','Footnotes','Quotations','Other_websites']
  20.  
  21. #Punctuation list to remove
  22. punctuation_list = ['\\','/',':',',','...','(',')','.','?','!','\"',';','\'']
  23.  
  24. #File name list to remove
  25. file_name_remove_list = ['_','-',' '] + punctuation_list
  26.  
  27. #File name to map document ids to document titles
  28. mapping_file_name = "document_id_mapping.txt"
  29.  
  30. #File to find the index of file names and urls
  31. index_of_file_names_and_urls = open('index-task1.txt', 'r')
  32. # ---- Code ----#
  33.  
  34. #grabs document names from index-task1
  35. def grab_document_names_from_index():
  36.     position = 0
  37.     document_dict = collections.OrderedDict()
  38.     for lines in index_of_file_names_and_urls:
  39.         position = position + 1
  40.         file_url = lines.split(str(position) + " - https://en.wikipedia.org/wiki/")
  41.         file_url = file_url[1]
  42.         file_url = file_url.split()
  43.         file_url = file_url[0]
  44.         file_url = ''.join(c for c in file_url if c not in file_name_remove_list) + ".txt"
  45.         document_dict[file_url] = position
  46.     return document_dict
  47.  
  48.  
  49.  
  50.  
  51. def open_document():
  52.     list_of_document_titles = []
  53.     document_index = collections.OrderedDict()
  54.     document_index = grab_document_names_from_index()
  55.     position = 0
  56.     for entry in document_index:
  57.         position = position+1
  58.         with open(directory_of_raw_documents + str(document_index[entry]), "r") as document:
  59.             html = document.read()
  60.             soup = BeautifulSoup(html, "html.parser")
  61.             body = soup.find('div', id='bodyContent')
  62.  
  63.             print("Processing document " + "(" + str(position) + "/" + str(amount_of_documents) + ")")
  64.  
  65.             #Clear tables
  66.             for table in body.find_all('table'): table.clear()
  67.  
  68.             #Clear content table
  69.             for div in body.find_all('div', {'id' : 'toc'}): div.decompose()
  70.  
  71.             #Clear hatnote
  72.             for class_item in body.find_all('div',{'class':'hatnote'}): class_item.decompose()
  73.  
  74.             #Clear images
  75.             for img in body.find_all('img'): img.decompose()
  76.  
  77.             #Clear references
  78.             for class_item in body.find_all('ol', {'class':'references'}): class_item.decompose()
  79.  
  80.             #Clear thumbs
  81.             for div in body.find_all('div', {'class':'thumb'}): div.decompose()
  82.  
  83.             #Clear navigations
  84.             for div in body.find_all('div', {'class': 'navbox'}): div.decompose()
  85.  
  86.             #Clear references by other names
  87.             for div in body.find_all('div', {'class': 'reflist'}): div.decompose()
  88.  
  89.             #Clear reference heading
  90.             for span in body.find_all('span',{'id': 'References'}): span.decompose()
  91.  
  92.             #Remove hidden div
  93.             for div in body.find_all('div',{'id': 'mw-hidden-catlinks'}): div.decompose()
  94.  
  95.             #remove site hub
  96.             for div in body.find_all('div',{'id': 'siteSub'}): div.decompose()
  97.  
  98.             #remove footer
  99.             for div in body.find_all('div', {'class': 'printfooter'}): div.decompose()
  100.  
  101.             #remove jump-to-nav
  102.             for div in body.find_all('div', {'id': 'jump-to-nav'}): div.decompose()
  103.  
  104.             #remove bottom navigation
  105.             for div in body.find_all('div', {'role':'navigation'}): div.decompose()
  106.  
  107.             #Grab content
  108.             results = ""
  109.             #for item in body.find_all(['h2','h3','p','li']):
  110.             #for item in body.find_all(['h2', 'h3', 'p', 'li']):
  111.                 #results += item.get_text() + " "
  112.                 #results = results.replace("[edit]", "")
  113.             results = body.get_text()
  114.             #results = results.encode('utf-8') #encodes it to stop weird errors
  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()
  147. string = 'major role — international and — international long-lived—many users’ consumer’s'
  148. print(remove_punctuation(string))
Advertisement
Add Comment
Please, Sign In to add comment