itsjube

Untitled

Nov 6th, 2016
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.75 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. #Punctuation list to remove
  17. punctuation_list = ['\\','/',':',',','...','(',')','.','?','!','\"',';','\'','’']
  18.  
  19. #File name list to remove
  20. file_name_remove_list = ['_','-',' '] + punctuation_list
  21.  
  22. #File name to map document ids to document titles
  23. mapping_file_name = "document_id_mapping.txt"
  24.  
  25. #File to find the index of file names and urls
  26. index_of_file_names_and_urls = open('index-task1.txt', 'r')
  27.  
  28. #List of headers to ignore
  29. ignore_list = ['See also']
  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) + ".txt - 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) + str(position) + ".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]) + ".txt", "r", encoding='utf-8') 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.             #Remove tables
  64.             for table in body.find_all('table'): table.clear()
  65.  
  66.             #Remove content table
  67.             for div in body.find_all('div', {'id' : 'toc'}): div.decompose()
  68.  
  69.             #Remove hatnote
  70.             for class_item in body.find_all('div',{'class':'hatnote'}): class_item.decompose()
  71.  
  72.             #Remove images
  73.             for img in body.find_all('img'): img.decompose()
  74.  
  75.             #Remove references
  76.             for class_item in body.find_all('ol', {'class':'references'}): class_item.decompose()
  77.  
  78.             #Remove thumbs
  79.             for div in body.find_all('div', {'class':'thumb'}): div.decompose()
  80.  
  81.             #Remove navigations
  82.             for div in body.find_all('div', {'class': 'navbox'}): div.decompose()
  83.  
  84.             #Remove references by other names
  85.             for div in body.find_all('div', {'class': 'reflist'}): div.decompose()
  86.  
  87.             #Remove reference heading
  88.             for span in body.find_all('span',{'id': 'References'}): span.decompose()
  89.  
  90.             #Remove hidden div
  91.             for div in body.find_all('div',{'id': 'mw-hidden-catlinks'}): div.decompose()
  92.  
  93.             #Remove site hub
  94.             for div in body.find_all('div',{'id': 'siteSub'}): div.decompose()
  95.  
  96.             #Remove footer
  97.             for div in body.find_all('div', {'class': 'printfooter'}): div.decompose()
  98.  
  99.             #Remove jump-to-nav
  100.             for div in body.find_all('div', {'id': 'jump-to-nav'}): div.decompose()
  101.  
  102.             #Remove bottom navigation
  103.             for div in body.find_all('div', {'role':'navigation'}): div.decompose()
  104.  
  105.             #Remove normal catlinks
  106.             for div in body.find_all('div', {'id': 'mw-normal-catlinks'}): div.decompose()
  107.  
  108.             # remove See_Also
  109.             previous_h2 = ""
  110.             try:
  111.                 for element in body.find_all(['h2', 'ul']):
  112.                     if (element.name == 'h2'):
  113.                         previous_h2 = element('span')[0].get_text()
  114.                         if(previous_h2 in ignore_list):
  115.                             print(element.find_previous_sibling('ul'))
  116.  
  117.             except(AttributeError, TypeError) as e:  # error where there is no previous h2
  118.                 continue
  119.             #Grab content
  120.             results = body.get_text()
  121.             results = results.replace('\n',' ')
  122.             results = results.replace('—', ' ')
  123.             results = results.replace('–',' ')
  124.             results = ' '.join(results.split())
  125.             results = re.sub('\[(.*?)\]','',results, flags=re.DOTALL) #removes [edit] and any citations
  126.             results = remove_punctuation(results) #removes punctuation
  127.             results = results.lower() #makes results lower
  128.  
  129.             #Save content to file
  130.             print("Saved to " + entry)
  131.             #saves the document
  132.             output_file = open(directory_of_parsed_documents + entry, 'w', encoding="utf-8")
  133.             output_file.write(results)
  134.             output_file.close()
  135.  
  136. #removes punctuation from provided string
  137. #but preserves punctuation between digits (I am allowing ALL punctuation)
  138. def remove_punctuation(string):
  139.     results = ""
  140.     previous = ""
  141.     next = ""
  142.     for i, c in enumerate(string):
  143.         if (i > 0):
  144.             previous = string[i - 1]
  145.         if (i + 1 != len(string)):
  146.             next = string[i + 1]
  147.         if (not previous.isdigit() or not next.isdigit()):  # if the previous and the next one are not digits
  148.             if(previous.isdigit() and c == "/"):
  149.                 results +=c
  150.             if (next.isdigit() and c == "/"):
  151.                 results += c
  152.             if (c not in punctuation_list):
  153.                 results += c
  154.         else:
  155.             results += c
  156.     return results
  157.  
  158. open_document()
Advertisement
Add Comment
Please, Sign In to add comment