PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/nltk/tokenize/texttiling.py

https://github.com/BrucePHill/nltk
Python | 459 lines | 412 code | 6 blank | 41 comment | 6 complexity | 556c55d67c3e6b7f8e16b474e1fb3e21 MD5 | raw file
Possible License(s): Apache-2.0
  1. # Natural Language Toolkit: TextTiling
  2. #
  3. # Copyright (C) 2001-2013 NLTK Project
  4. # Author: George Boutsioukis
  5. #
  6. # URL: <http://www.nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. import re
  9. import math
  10. try:
  11. import numpy
  12. except ImportError:
  13. pass
  14. from nltk.tokenize.api import TokenizerI
  15. BLOCK_COMPARISON, VOCABULARY_INTRODUCTION = 0, 1
  16. LC, HC = 0, 1
  17. DEFAULT_SMOOTHING = [0]
  18. class TextTilingTokenizer(TokenizerI):
  19. """Tokenize a document into topical sections using the TextTiling algorithm.
  20. This algorithm detects subtopic shifts based on the analysis of lexical
  21. co-occurrence patterns.
  22. The process starts by tokenizing the text into pseudosentences of
  23. a fixed size w. Then, depending on the method used, similarity
  24. scores are assigned at sentence gaps. The algorithm proceeds by
  25. detecting the peak differences between these scores and marking
  26. them as boundaries. The boundaries are normalized to the closest
  27. paragraph break and the segmented text is returned.
  28. :param w: Pseudosentence size
  29. :type w: int
  30. :param k: Size (in sentences) of the block used in the block comparison method
  31. :type k: int
  32. :param similarity_method: The method used for determining similarity scores:
  33. `BLOCK_COMPARISON` (default) or `VOCABULARY_INTRODUCTION`.
  34. :type similarity_method: constant
  35. :param stopwords: A list of stopwords that are filtered out (defaults to NLTK's stopwords corpus)
  36. :type stopwords: list(str)
  37. :param smoothing_method: The method used for smoothing the score plot:
  38. `DEFAULT_SMOOTHING` (default)
  39. :type smoothing_method: constant
  40. :param smoothing_width: The width of the window used by the smoothing method
  41. :type smoothing_width: int
  42. :param smoothing_rounds: The number of smoothing passes
  43. :type smoothing_rounds: int
  44. :param cutoff_policy: The policy used to determine the number of boundaries:
  45. `HC` (default) or `LC`
  46. :type cutoff_policy: constant
  47. """
  48. def __init__(self,
  49. w=20,
  50. k=10,
  51. similarity_method=BLOCK_COMPARISON,
  52. stopwords=None,
  53. smoothing_method=DEFAULT_SMOOTHING,
  54. smoothing_width=2,
  55. smoothing_rounds=1,
  56. cutoff_policy=HC,
  57. demo_mode=False):
  58. if stopwords is None:
  59. from nltk.corpus import stopwords
  60. stopwords = stopwords.words('english')
  61. self.__dict__.update(locals())
  62. del self.__dict__['self']
  63. def tokenize(self, text):
  64. """Return a tokenized copy of *text*, where each "token" represents
  65. a separate topic."""
  66. lowercase_text = text.lower()
  67. paragraph_breaks = self._mark_paragraph_breaks(text)
  68. text_length = len(lowercase_text)
  69. # Tokenization step starts here
  70. # Remove punctuation
  71. nopunct_text = ''.join(c for c in lowercase_text
  72. if re.match("[a-z\-\' \n\t]", c))
  73. nopunct_par_breaks = self._mark_paragraph_breaks(nopunct_text)
  74. tokseqs = self._divide_to_tokensequences(nopunct_text)
  75. # The morphological stemming step mentioned in the TextTile
  76. # paper is not implemented. A comment in the original C
  77. # implementation states that it offers no benefit to the
  78. # process. It might be interesting to test the existing
  79. # stemmers though.
  80. #words = _stem_words(words)
  81. # Filter stopwords
  82. for ts in tokseqs:
  83. ts.wrdindex_list = [wi for wi in ts.wrdindex_list
  84. if wi[0] not in self.stopwords]
  85. token_table = self._create_token_table(tokseqs, nopunct_par_breaks)
  86. # End of the Tokenization step
  87. # Lexical score determination
  88. if self.similarity_method == BLOCK_COMPARISON:
  89. gap_scores = self._block_comparison(tokseqs, token_table)
  90. elif self.similarity_method == VOCABULARY_INTRODUCTION:
  91. raise NotImplementedError("Vocabulary introduction not implemented")
  92. if self.smoothing_method == DEFAULT_SMOOTHING:
  93. smooth_scores = self._smooth_scores(gap_scores)
  94. # End of Lexical score Determination
  95. # Boundary identification
  96. depth_scores = self._depth_scores(smooth_scores)
  97. segment_boundaries = self._identify_boundaries(depth_scores)
  98. normalized_boundaries = self._normalize_boundaries(text,
  99. segment_boundaries,
  100. paragraph_breaks)
  101. # End of Boundary Identification
  102. segmented_text = []
  103. prevb = 0
  104. for b in normalized_boundaries:
  105. if b == 0:
  106. continue
  107. segmented_text.append(text[prevb:b])
  108. prevb = b
  109. if prevb < text_length: # append any text that may be remaining
  110. segmented_text.append(text[prevb:])
  111. if not segmented_text:
  112. segmented_text = [text]
  113. if self.demo_mode:
  114. return gap_scores, smooth_scores, depth_scores, segment_boundaries
  115. return segmented_text
  116. def _block_comparison(self, tokseqs, token_table):
  117. "Implements the block comparison method"
  118. def blk_frq(tok, block):
  119. ts_occs = filter(lambda o: o[0] in block,
  120. token_table[tok].ts_occurences)
  121. freq = sum([tsocc[1] for tsocc in ts_occs])
  122. return freq
  123. gap_scores = []
  124. numgaps = len(tokseqs)-1
  125. for curr_gap in range(numgaps):
  126. score_dividend, score_divisor_b1, score_divisor_b2 = 0.0, 0.0, 0.0
  127. score = 0.0
  128. #adjust window size for boundary conditions
  129. if curr_gap < self.k-1:
  130. window_size = curr_gap + 1
  131. elif curr_gap > numgaps-self.k:
  132. window_size = numgaps - curr_gap
  133. else:
  134. window_size = self.k
  135. b1 = [ts.index
  136. for ts in tokseqs[curr_gap-window_size+1 : curr_gap+1]]
  137. b2 = [ts.index
  138. for ts in tokseqs[curr_gap+1 : curr_gap+window_size+1]]
  139. for t in token_table:
  140. score_dividend += blk_frq(t, b1)*blk_frq(t, b2)
  141. score_divisor_b1 += blk_frq(t, b1)**2
  142. score_divisor_b2 += blk_frq(t, b2)**2
  143. try:
  144. score = score_dividend/math.sqrt(score_divisor_b1*
  145. score_divisor_b2)
  146. except ZeroDivisionError:
  147. pass # score += 0.0
  148. gap_scores.append(score)
  149. return gap_scores
  150. def _smooth_scores(self, gap_scores):
  151. "Wraps the smooth function from the SciPy Cookbook"
  152. return list(smooth(numpy.array(gap_scores[:]),
  153. window_len = self.smoothing_width+1))
  154. def _mark_paragraph_breaks(self, text):
  155. """Identifies indented text or line breaks as the beginning of
  156. paragraphs"""
  157. MIN_PARAGRAPH = 100
  158. pattern = re.compile("[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*")
  159. matches = pattern.finditer(text)
  160. last_break = 0
  161. pbreaks = [0]
  162. for pb in matches:
  163. if pb.start()-last_break < MIN_PARAGRAPH:
  164. continue
  165. else:
  166. pbreaks.append(pb.start())
  167. last_break = pb.start()
  168. return pbreaks
  169. def _divide_to_tokensequences(self, text):
  170. "Divides the text into pseudosentences of fixed size"
  171. w = self.w
  172. wrdindex_list = []
  173. matches = re.finditer("\w+", text)
  174. for match in matches:
  175. wrdindex_list.append((match.group(), match.start()))
  176. return [TokenSequence(i/w, wrdindex_list[i:i+w])
  177. for i in range(0, len(wrdindex_list), w)]
  178. def _create_token_table(self, token_sequences, par_breaks):
  179. "Creates a table of TokenTableFields"
  180. token_table = {}
  181. current_par = 0
  182. current_tok_seq = 0
  183. pb_iter = par_breaks.__iter__()
  184. current_par_break = next(pb_iter)
  185. if current_par_break == 0:
  186. try:
  187. current_par_break = next(pb_iter) #skip break at 0
  188. except StopIteration:
  189. raise ValueError(
  190. "No paragraph breaks were found(text too short perhaps?)"
  191. )
  192. for ts in token_sequences:
  193. for word, index in ts.wrdindex_list:
  194. try:
  195. while index > current_par_break:
  196. current_par_break = next(pb_iter)
  197. current_par += 1
  198. except StopIteration:
  199. #hit bottom
  200. pass
  201. if word in token_table:
  202. token_table[word].total_count += 1
  203. if token_table[word].last_par != current_par:
  204. token_table[word].last_par = current_par
  205. token_table[word].par_count += 1
  206. if token_table[word].last_tok_seq != current_tok_seq:
  207. token_table[word].last_tok_seq = current_tok_seq
  208. token_table[word]\
  209. .ts_occurences.append([current_tok_seq,1])
  210. else:
  211. token_table[word].ts_occurences[-1][1] += 1
  212. else: #new word
  213. token_table[word] = TokenTableField(first_pos=index,
  214. ts_occurences= \
  215. [[current_tok_seq,1]],
  216. total_count=1,
  217. par_count=1,
  218. last_par=current_par,
  219. last_tok_seq= \
  220. current_tok_seq)
  221. current_tok_seq += 1
  222. return token_table
  223. def _identify_boundaries(self, depth_scores):
  224. """Identifies boundaries at the peaks of similarity score
  225. differences"""
  226. boundaries = [0 for x in depth_scores]
  227. avg = sum(depth_scores)/len(depth_scores)
  228. numpy.stdev = numpy.std(depth_scores)
  229. #SB: what is the purpose of this conditional?
  230. if self.cutoff_policy == LC:
  231. cutoff = avg-numpy.stdev/2.0
  232. else:
  233. cutoff = avg-numpy.stdev/2.0
  234. depth_tuples = sorted(zip(depth_scores, range(len(depth_scores))))
  235. depth_tuples.reverse()
  236. hp = filter(lambda x:x[0]>cutoff, depth_tuples)
  237. for dt in hp:
  238. boundaries[dt[1]] = 1
  239. for dt2 in hp: #undo if there is a boundary close already
  240. if dt[1] != dt2[1] and abs(dt2[1]-dt[1]) < 4 \
  241. and boundaries[dt2[1]] == 1:
  242. boundaries[dt[1]] = 0
  243. return boundaries
  244. def _depth_scores(self, scores):
  245. """Calculates the depth of each gap, i.e. the average difference
  246. between the left and right peaks and the gap's score"""
  247. depth_scores = [0 for x in scores]
  248. #clip boundaries: this holds on the rule of thumb(my thumb)
  249. #that a section shouldn't be smaller than at least 2
  250. #pseudosentences for small texts and around 5 for larger ones.
  251. clip = min(max(len(scores)/10, 2), 5)
  252. index = clip
  253. # SB: next three lines are redundant as depth_scores is already full of zeros
  254. for i in range(clip):
  255. depth_scores[i] = 0
  256. depth_scores[-i-1] = 0
  257. for gapscore in scores[clip:-clip]:
  258. lpeak = gapscore
  259. for score in scores[index::-1]:
  260. if score >= lpeak:
  261. lpeak = score
  262. else:
  263. break
  264. rpeak = gapscore
  265. for score in scores[:index:]:
  266. if score >= rpeak:
  267. rpeak=score
  268. else:
  269. break
  270. depth_scores[index] = lpeak + rpeak - 2*gapscore
  271. index += 1
  272. return depth_scores
  273. def _normalize_boundaries(self, text, boundaries, paragraph_breaks):
  274. """Normalize the boundaries identified to the original text's
  275. paragraph breaks"""
  276. norm_boundaries = []
  277. char_count, word_count, gaps_seen = 0, 0, 0
  278. seen_word = False
  279. for char in text:
  280. char_count += 1
  281. if char in " \t\n" and seen_word:
  282. seen_word = False
  283. word_count += 1
  284. if char not in " \t\n" and not seen_word:
  285. seen_word=True
  286. if gaps_seen < len(boundaries) and word_count > \
  287. (max(gaps_seen*self.w, self.w)):
  288. if boundaries[gaps_seen] == 1:
  289. #find closest paragraph break
  290. best_fit = len(text)
  291. for br in paragraph_breaks:
  292. if best_fit > abs(br-char_count):
  293. best_fit = abs(br-char_count)
  294. bestbr = br
  295. else:
  296. break
  297. if bestbr not in norm_boundaries: #avoid duplicates
  298. norm_boundaries.append(bestbr)
  299. gaps_seen += 1
  300. return norm_boundaries
  301. class TokenTableField(object):
  302. """A field in the token table holding parameters for each token,
  303. used later in the process"""
  304. def __init__(self,
  305. first_pos,
  306. ts_occurences,
  307. total_count=1,
  308. par_count=1,
  309. last_par=0,
  310. last_tok_seq=None):
  311. self.__dict__.update(locals())
  312. del self.__dict__['self']
  313. class TokenSequence(object):
  314. "A token list with its original length and its index"
  315. def __init__(self,
  316. index,
  317. wrdindex_list,
  318. original_length=None):
  319. original_length=original_length or len(wrdindex_list)
  320. self.__dict__.update(locals())
  321. del self.__dict__['self']
  322. #Pasted from the SciPy cookbook: http://www.scipy.org/Cookbook/SignalSmooth
  323. def smooth(x,window_len=11,window='flat'):
  324. """smooth the data using a window with requested size.
  325. This method is based on the convolution of a scaled window with the signal.
  326. The signal is prepared by introducing reflected copies of the signal
  327. (with the window size) in both ends so that transient parts are minimized
  328. in the beginning and end part of the output signal.
  329. :param x: the input signal
  330. :param window_len: the dimension of the smoothing window; should be an odd integer
  331. :param window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
  332. flat window will produce a moving average smoothing.
  333. :return: the smoothed signal
  334. example::
  335. t=linspace(-2,2,0.1)
  336. x=sin(t)+randn(len(t))*0.1
  337. y=smooth(x)
  338. :see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve,
  339. scipy.signal.lfilter
  340. TODO: the window parameter could be the window itself if an array instead of a string
  341. """
  342. if x.ndim != 1:
  343. raise ValueError("smooth only accepts 1 dimension arrays.")
  344. if x.size < window_len:
  345. raise ValueError("Input vector needs to be bigger than window size.")
  346. if window_len<3:
  347. return x
  348. if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
  349. raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
  350. s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]]
  351. #print(len(s))
  352. if window == 'flat': #moving average
  353. w=numpy.ones(window_len,'d')
  354. else:
  355. w=eval('numpy.'+window+'(window_len)')
  356. y=numpy.convolve(w/w.sum(),s,mode='same')
  357. return y[window_len-1:-window_len+1]
  358. def demo(text=None):
  359. from nltk.corpus import brown
  360. import pylab
  361. tt=TextTilingTokenizer(demo_mode=True)
  362. if text is None: text=brown.raw()[:10000]
  363. s,ss,d,b=tt.tokenize(text)
  364. pylab.xlabel("Sentence Gap index")
  365. pylab.ylabel("Gap Scores")
  366. pylab.plot(range(len(s)), s, label="Gap Scores")
  367. pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores")
  368. pylab.plot(range(len(d)), d, label="Depth scores")
  369. pylab.stem(range(len(b)),b)
  370. pylab.legend()
  371. pylab.show()
  372. if __name__ == "__main__":
  373. import doctest
  374. doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)