itsjube

Untitled

Nov 5th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.15 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 = ['Contents','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. #Grab content
  67. results = ""
  68. for item in body.find_all(['h2','h3','p','li']):
  69. try:
  70. if item.name != 'h2': #We are not in the h2, therefore, lets find the id of the previous h2
  71. parent_h2_id = item.find_previous_sibling('h2').find('span')['id']
  72. else:
  73. parent_h2_id = item.find('span')['id']#If we are in the h2, get the ID.
  74. except (AttributeError, TypeError) as e: #error where there is no previous h2
  75. parent_h2_id = None
  76. if parent_h2_id and parent_h2_id in ignore_list:
  77. continue
  78. else:
  79. results += item.get_text() + "\n"
  80. #results = results.replace("[edit]", "")
  81. results = results.encode('utf-8') #encodes it to stop weird errors
  82. results = re.sub('\[(.*?)\]','',results, flags=re.DOTALL) #removes [edit] and any citations
  83. results = remove_punctuation(results) #removes punctuation
  84. results = results.lower() #makes results lower
  85.  
  86.  
  87. print("Saved to " + entry)
  88. #saves the document
  89. output_file = open(directory_of_parsed_documents + entry, 'w')
  90. output_file.write(results)
  91. output_file.close()
  92.  
  93. #removes punctuation from provided string
  94. #but preserves punctuation between digits (I am allowing ALL punctuation)
  95. def remove_punctuation(string):
  96. results = ""
  97. previous = ""
  98. next = ""
  99. for i, c in enumerate(string):
  100. if (i > 0):
  101. previous = string[i - 1]
  102. if (i + 1 != len(string)):
  103. next = string[i + 1]
  104. if (not previous.isdigit() or not next.isdigit()): # if the previous and the next one are not digits
  105. if (c not in punctuation_list):
  106. results += c
  107. else:
  108. results += c
  109. return results
  110.  
  111. open_document()
Advertisement
Add Comment
Please, Sign In to add comment