portuguese_en.doctest 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. .. Copyright (C) 2001-2020 NLTK Project
  2. .. For license information, see LICENSE.TXT
  3. ==================================
  4. Examples for Portuguese Processing
  5. ==================================
  6. This HOWTO contains a variety of examples relating to the Portuguese language.
  7. It is intended to be read in conjunction with the NLTK book
  8. (``http://nltk.org/book``). For instructions on running the Python
  9. interpreter, please see the section *Getting Started with Python*, in Chapter 1.
  10. --------------------------------------------
  11. Python Programming, with Portuguese Examples
  12. --------------------------------------------
  13. Chapter 1 of the NLTK book contains many elementary programming examples, all
  14. with English texts. In this section, we'll see some corresponding examples
  15. using Portuguese. Please refer to the chapter for full discussion. *Vamos!*
  16. >>> from nltk.examples.pt import *
  17. *** Introductory Examples for the NLTK Book ***
  18. Loading ptext1, ... and psent1, ...
  19. Type the name of the text or sentence to view it.
  20. Type: 'texts()' or 'sents()' to list the materials.
  21. ptext1: Memórias Póstumas de Brás Cubas (1881)
  22. ptext2: Dom Casmurro (1899)
  23. ptext3: Gênesis
  24. ptext4: Folha de Sao Paulo (1994)
  25. Any time we want to find out about these texts, we just have
  26. to enter their names at the Python prompt:
  27. >>> ptext2
  28. <Text: Dom Casmurro (1899)>
  29. Searching Text
  30. --------------
  31. A concordance permits us to see words in context.
  32. >>> ptext1.concordance('olhos')
  33. Building index...
  34. Displaying 25 of 138 matches:
  35. De pé , à cabeceira da cama , com os olhos estúpidos , a boca entreaberta , a t
  36. orelhas . Pela minha parte fechei os olhos e deixei - me ir à ventura . Já agor
  37. xões de cérebro enfermo . Como ia de olhos fechados , não via o caminho ; lembr
  38. gelos eternos . Com efeito , abri os olhos e vi que o meu animal galopava numa
  39. me apareceu então , fitando - me uns olhos rutilantes como o sol . Tudo nessa f
  40. mim mesmo . Então , encarei - a com olhos súplices , e pedi mais alguns anos .
  41. ...
  42. For a given word, we can find words with a similar text distribution:
  43. >>> ptext1.similar('chegar')
  44. Building word-context index...
  45. acabada acudir aludir avistar bramanismo casamento cheguei com contar
  46. contrário corpo dali deixei desferirem dizer fazer filhos já leitor lhe
  47. >>> ptext3.similar('chegar')
  48. Building word-context index...
  49. achar alumiar arrombar destruir governar guardar ir lavrar passar que
  50. toda tomar ver vir
  51. We can search for the statistically significant collocations in a text:
  52. >>> ptext1.collocations()
  53. Building collocations list
  54. Quincas Borba; Lobo Neves; alguma coisa; Brás Cubas; meu pai; dia
  55. seguinte; não sei; Meu pai; alguns instantes; outra vez; outra coisa;
  56. por exemplo; mim mesmo; coisa nenhuma; mesma coisa; não era; dias
  57. depois; Passeio Público; olhar para; das coisas
  58. We can search for words in context, with the help of *regular expressions*, e.g.:
  59. >>> ptext1.findall("<olhos> (<.*>)")
  60. estúpidos; e; fechados; rutilantes; súplices; a; do; babavam;
  61. na; moles; se; da; umas; espraiavam; chamejantes; espetados;
  62. ...
  63. We can automatically generate random text based on a given text, e.g.:
  64. >>> ptext3.generate() # doctest: +SKIP
  65. No princípio , criou Deus os abençoou , dizendo : Onde { estão } e até
  66. à ave dos céus , { que } será . Disse mais Abrão : Dá - me a mulher
  67. que tomaste ; porque daquele poço Eseque , { tinha .} E disse : Não
  68. poderemos descer ; mas , do campo ainda não estava na casa do teu
  69. pescoço . E viveu Serugue , depois Simeão e Levi { são } estes ? E o
  70. varão , porque habitava na terra de Node , da mão de Esaú : Jeús ,
  71. Jalão e Corá
  72. Texts as List of Words
  73. ----------------------
  74. A few sentences have been defined for you.
  75. >>> psent1
  76. ['o', 'amor', 'da', 'gl\xf3ria', 'era', 'a', 'coisa', 'mais',
  77. 'verdadeiramente', 'humana', 'que', 'h\xe1', 'no', 'homem', ',',
  78. 'e', ',', 'conseq\xfcentemente', ',', 'a', 'sua', 'mais',
  79. 'genu\xedna', 'fei\xe7\xe3o', '.']
  80. >>>
  81. Notice that the sentence has been *tokenized*. Each token is
  82. represented as a string, represented using quotes, e.g. ``'coisa'``.
  83. Some strings contain special characters, e.g. ``\xf3``,
  84. the internal representation for ó.
  85. The tokens are combined in the form of a *list*. How long is this list?
  86. >>> len(psent1)
  87. 25
  88. >>>
  89. What is the vocabulary of this sentence?
  90. >>> sorted(set(psent1))
  91. [',', '.', 'a', 'amor', 'coisa', 'conseqüentemente', 'da', 'e', 'era',
  92. 'feição', 'genuína', 'glória', 'homem', 'humana', 'há', 'mais', 'no',
  93. 'o', 'que', 'sua', 'verdadeiramente']
  94. >>>
  95. Let's iterate over each item in ``psent2``, and print information for each:
  96. >>> for w in psent2:
  97. ... print(w, len(w), w[-1])
  98. ...
  99. Não 3 o
  100. consultes 9 s
  101. dicionários 11 s
  102. . 1 .
  103. Observe how we make a human-readable version of a string, using ``decode()``.
  104. Also notice that we accessed the last character of a string ``w`` using ``w[-1]``.
  105. We just saw a ``for`` loop above. Another useful control structure is a
  106. *list comprehension*.
  107. >>> [w.upper() for w in psent2]
  108. ['N\xc3O', 'CONSULTES', 'DICION\xc1RIOS', '.']
  109. >>> [w for w in psent1 if w.endswith('a')]
  110. ['da', 'gl\xf3ria', 'era', 'a', 'coisa', 'humana', 'a', 'sua', 'genu\xedna']
  111. >>> [w for w in ptext4 if len(w) > 15]
  112. ['norte-irlandeses', 'pan-nacionalismo', 'predominatemente', 'primeiro-ministro',
  113. 'primeiro-ministro', 'irlandesa-americana', 'responsabilidades', 'significativamente']
  114. We can examine the relative frequency of words in a text, using ``FreqDist``:
  115. >>> fd1 = FreqDist(ptext1)
  116. >>> fd1
  117. <FreqDist with 10848 samples and 77098 outcomes>
  118. >>> fd1['olhos']
  119. 137
  120. >>> fd1.max()
  121. ','
  122. >>> fd1.samples()[:100]
  123. [',', '.', 'a', 'que', 'de', 'e', '-', 'o', ';', 'me', 'um', 'n\xe3o',
  124. '\x97', 'se', 'do', 'da', 'uma', 'com', 'os', '\xe9', 'era', 'as', 'eu',
  125. 'lhe', 'ao', 'em', 'para', 'mas', '...', '!', '\xe0', 'na', 'mais', '?',
  126. 'no', 'como', 'por', 'N\xe3o', 'dos', 'o', 'ele', ':', 'Virg\xedlia',
  127. 'me', 'disse', 'minha', 'das', 'O', '/', 'A', 'CAP\xcdTULO', 'muito',
  128. 'depois', 'coisa', 'foi', 'sem', 'olhos', 'ela', 'nos', 'tinha', 'nem',
  129. 'E', 'outro', 'vida', 'nada', 'tempo', 'menos', 'outra', 'casa', 'homem',
  130. 'porque', 'quando', 'mim', 'mesmo', 'ser', 'pouco', 'estava', 'dia',
  131. 't\xe3o', 'tudo', 'Mas', 'at\xe9', 'D', 'ainda', 's\xf3', 'alguma',
  132. 'la', 'vez', 'anos', 'h\xe1', 'Era', 'pai', 'esse', 'lo', 'dizer', 'assim',
  133. 'ent\xe3o', 'dizia', 'aos', 'Borba']
  134. ---------------
  135. Reading Corpora
  136. ---------------
  137. Accessing the Machado Text Corpus
  138. ---------------------------------
  139. NLTK includes the complete works of Machado de Assis.
  140. >>> from nltk.corpus import machado
  141. >>> machado.fileids()
  142. ['contos/macn001.txt', 'contos/macn002.txt', 'contos/macn003.txt', ...]
  143. Each file corresponds to one of the works of Machado de Assis. To see a complete
  144. list of works, you can look at the corpus README file: ``print machado.readme()``.
  145. Let's access the text of the *Posthumous Memories of Brás Cubas*.
  146. We can access the text as a list of characters, and access 200 characters starting
  147. from position 10,000.
  148. >>> raw_text = machado.raw('romance/marm05.txt')
  149. >>> raw_text[10000:10200]
  150. u', primou no\nEstado, e foi um dos amigos particulares do vice-rei Conde
  151. da Cunha.\n\nComo este apelido de Cubas lhe\ncheirasse excessivamente a
  152. tanoaria, alegava meu pai, bisneto de Dami\xe3o, que o\ndito ape'
  153. However, this is not a very useful way to work with a text. We generally think
  154. of a text as a sequence of words and punctuation, not characters:
  155. >>> text1 = machado.words('romance/marm05.txt')
  156. >>> text1
  157. ['Romance', ',', 'Mem\xf3rias', 'P\xf3stumas', 'de', ...]
  158. >>> len(text1)
  159. 77098
  160. >>> len(set(text1))
  161. 10848
  162. Here's a program that finds the most common ngrams that contain a
  163. particular target word.
  164. >>> from nltk import ngrams, FreqDist
  165. >>> target_word = 'olhos'
  166. >>> fd = FreqDist(ng
  167. ... for ng in ngrams(text1, 5)
  168. ... if target_word in ng)
  169. >>> for hit in fd.samples():
  170. ... print(' '.join(hit))
  171. ...
  172. , com os olhos no
  173. com os olhos no ar
  174. com os olhos no chão
  175. e todos com os olhos
  176. me estar com os olhos
  177. os olhos estúpidos , a
  178. os olhos na costura ,
  179. os olhos no ar ,
  180. , com os olhos espetados
  181. , com os olhos estúpidos
  182. , com os olhos fitos
  183. , com os olhos naquele
  184. , com os olhos para
  185. Accessing the MacMorpho Tagged Corpus
  186. -------------------------------------
  187. NLTK includes the MAC-MORPHO Brazilian Portuguese POS-tagged news text,
  188. with over a million words of
  189. journalistic texts extracted from ten sections of
  190. the daily newspaper *Folha de Sao Paulo*, 1994.
  191. We can access this corpus as a sequence of words or tagged words as follows:
  192. >>> import nltk.corpus
  193. >>> nltk.corpus.mac_morpho.words()
  194. ['Jersei', 'atinge', 'm\xe9dia', 'de', 'Cr$', '1,4', ...]
  195. >>> nltk.corpus.mac_morpho.sents() # doctest: +NORMALIZE_WHITESPACE
  196. [['Jersei', 'atinge', 'm\xe9dia', 'de', 'Cr$', '1,4', 'milh\xe3o',
  197. 'em', 'a', 'venda', 'de', 'a', 'Pinhal', 'em', 'S\xe3o', 'Paulo'],
  198. ['Programe', 'sua', 'viagem', 'a', 'a', 'Exposi\xe7\xe3o', 'Nacional',
  199. 'do', 'Zeb', ',', 'que', 'come\xe7a', 'dia', '25'], ...]
  200. >>> nltk.corpus.mac_morpho.tagged_words()
  201. [('Jersei', 'N'), ('atinge', 'V'), ('m\xe9dia', 'N'), ...]
  202. We can also access it in sentence chunks.
  203. >>> nltk.corpus.mac_morpho.tagged_sents() # doctest: +NORMALIZE_WHITESPACE
  204. [[('Jersei', 'N'), ('atinge', 'V'), ('m\xe9dia', 'N'), ('de', 'PREP'),
  205. ('Cr$', 'CUR'), ('1,4', 'NUM'), ('milh\xe3o', 'N'), ('em', 'PREP|+'),
  206. ('a', 'ART'), ('venda', 'N'), ('de', 'PREP|+'), ('a', 'ART'),
  207. ('Pinhal', 'NPROP'), ('em', 'PREP'), ('S\xe3o', 'NPROP'),
  208. ('Paulo', 'NPROP')],
  209. [('Programe', 'V'), ('sua', 'PROADJ'), ('viagem', 'N'), ('a', 'PREP|+'),
  210. ('a', 'ART'), ('Exposi\xe7\xe3o', 'NPROP'), ('Nacional', 'NPROP'),
  211. ('do', 'NPROP'), ('Zeb', 'NPROP'), (',', ','), ('que', 'PRO-KS-REL'),
  212. ('come\xe7a', 'V'), ('dia', 'N'), ('25', 'N|AP')], ...]
  213. This data can be used to train taggers (examples below for the Floresta treebank).
  214. Accessing the Floresta Portuguese Treebank
  215. ------------------------------------------
  216. The NLTK data distribution includes the
  217. "Floresta Sinta(c)tica Corpus" version 7.4, available from
  218. ``http://www.linguateca.pt/Floresta/``.
  219. We can access this corpus as a sequence of words or tagged words as follows:
  220. >>> from nltk.corpus import floresta
  221. >>> floresta.words()
  222. ['Um', 'revivalismo', 'refrescante', 'O', '7_e_Meio', ...]
  223. >>> floresta.tagged_words()
  224. [('Um', '>N+art'), ('revivalismo', 'H+n'), ...]
  225. The tags consist of some syntactic information, followed by a plus sign,
  226. followed by a conventional part-of-speech tag. Let's strip off the material before
  227. the plus sign:
  228. >>> def simplify_tag(t):
  229. ... if "+" in t:
  230. ... return t[t.index("+")+1:]
  231. ... else:
  232. ... return t
  233. >>> twords = floresta.tagged_words()
  234. >>> twords = [(w.lower(), simplify_tag(t)) for (w,t) in twords]
  235. >>> twords[:10]
  236. [('um', 'art'), ('revivalismo', 'n'), ('refrescante', 'adj'), ('o', 'art'), ('7_e_meio', 'prop'),
  237. ('\xe9', 'v-fin'), ('um', 'art'), ('ex-libris', 'n'), ('de', 'prp'), ('a', 'art')]
  238. Pretty printing the tagged words:
  239. >>> print(' '.join(word + '/' + tag for (word, tag) in twords[:10]))
  240. um/art revivalismo/n refrescante/adj o/art 7_e_meio/prop é/v-fin um/art ex-libris/n de/prp a/art
  241. Count the word tokens and types, and determine the most common word:
  242. >>> words = floresta.words()
  243. >>> len(words)
  244. 211852
  245. >>> fd = nltk.FreqDist(words)
  246. >>> len(fd)
  247. 29421
  248. >>> fd.max()
  249. 'de'
  250. List the 20 most frequent tags, in order of decreasing frequency:
  251. >>> tags = [simplify_tag(tag) for (word,tag) in floresta.tagged_words()]
  252. >>> fd = nltk.FreqDist(tags)
  253. >>> fd.keys()[:20] # doctest: +NORMALIZE_WHITESPACE
  254. ['n', 'prp', 'art', 'v-fin', ',', 'prop', 'adj', 'adv', '.',
  255. 'conj-c', 'v-inf', 'pron-det', 'v-pcp', 'num', 'pron-indp',
  256. 'pron-pers', '\xab', '\xbb', 'conj-s', '}']
  257. We can also access the corpus grouped by sentence:
  258. >>> floresta.sents() # doctest: +NORMALIZE_WHITESPACE
  259. [['Um', 'revivalismo', 'refrescante'],
  260. ['O', '7_e_Meio', '\xe9', 'um', 'ex-libris', 'de', 'a', 'noite',
  261. 'algarvia', '.'], ...]
  262. >>> floresta.tagged_sents() # doctest: +NORMALIZE_WHITESPACE
  263. [[('Um', '>N+art'), ('revivalismo', 'H+n'), ('refrescante', 'N<+adj')],
  264. [('O', '>N+art'), ('7_e_Meio', 'H+prop'), ('\xe9', 'P+v-fin'),
  265. ('um', '>N+art'), ('ex-libris', 'H+n'), ('de', 'H+prp'),
  266. ('a', '>N+art'), ('noite', 'H+n'), ('algarvia', 'N<+adj'), ('.', '.')],
  267. ...]
  268. >>> floresta.parsed_sents() # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
  269. [Tree('UTT+np', [Tree('>N+art', ['Um']), Tree('H+n', ['revivalismo']),
  270. Tree('N<+adj', ['refrescante'])]),
  271. Tree('STA+fcl',
  272. [Tree('SUBJ+np', [Tree('>N+art', ['O']),
  273. Tree('H+prop', ['7_e_Meio'])]),
  274. Tree('P+v-fin', ['\xe9']),
  275. Tree('SC+np',
  276. [Tree('>N+art', ['um']),
  277. Tree('H+n', ['ex-libris']),
  278. Tree('N<+pp', [Tree('H+prp', ['de']),
  279. Tree('P<+np', [Tree('>N+art', ['a']),
  280. Tree('H+n', ['noite']),
  281. Tree('N<+adj', ['algarvia'])])])]),
  282. Tree('.', ['.'])]), ...]
  283. To view a parse tree, use the ``draw()`` method, e.g.:
  284. >>> psents = floresta.parsed_sents()
  285. >>> psents[5].draw() # doctest: +SKIP
  286. Character Encodings
  287. -------------------
  288. Python understands the common character encoding used for Portuguese, ISO 8859-1 (ISO Latin 1).
  289. >>> import os, nltk.test
  290. >>> testdir = os.path.split(nltk.test.__file__)[0]
  291. >>> text = open(os.path.join(testdir, 'floresta.txt'), 'rb').read().decode('ISO 8859-1')
  292. >>> text[:60]
  293. 'O 7 e Meio \xe9 um ex-libris da noite algarvia.\n\xc9 uma das mais '
  294. >>> print(text[:60])
  295. O 7 e Meio é um ex-libris da noite algarvia.
  296. É uma das mais
  297. For more information about character encodings and Python, please see section 3.3 of the book.
  298. ----------------
  299. Processing Tasks
  300. ----------------
  301. Simple Concordancing
  302. --------------------
  303. Here's a function that takes a word and a specified amount of context (measured
  304. in characters), and generates a concordance for that word.
  305. >>> def concordance(word, context=30):
  306. ... for sent in floresta.sents():
  307. ... if word in sent:
  308. ... pos = sent.index(word)
  309. ... left = ' '.join(sent[:pos])
  310. ... right = ' '.join(sent[pos+1:])
  311. ... print('%*s %s %-*s' %
  312. ... (context, left[-context:], word, context, right[:context]))
  313. >>> concordance("dar") # doctest: +SKIP
  314. anduru , foi o suficiente para dar a volta a o resultado .
  315. 1. O P?BLICO veio dar a a imprensa di?ria portuguesa
  316. A fartura de pensamento pode dar maus resultados e n?s n?o quer
  317. Come?a a dar resultados a pol?tica de a Uni
  318. ial come?ar a incorporar- lo e dar forma a um ' site ' que tem se
  319. r com Constantino para ele lhe dar tamb?m os pap?is assinados .
  320. va a brincar , pois n?o lhe ia dar procura??o nenhuma enquanto n?
  321. ?rica como o ant?doto capaz de dar sentido a o seu enorme poder .
  322. . . .
  323. >>> concordance("vender") # doctest: +SKIP
  324. er recebido uma encomenda para vender 4000 blindados a o Iraque .
  325. m?rico_Amorim caso conseguisse vender o lote de ac??es de o empres?r
  326. mpre ter jovens simp?ticos a ? vender ? chega ! }
  327. Disse que o governo vai vender ? desde autom?vel at? particip
  328. ndiciou ontem duas pessoas por vender carro com ?gio .
  329. A inten??o de Fleury ? vender as a??es para equilibrar as fi
  330. Part-of-Speech Tagging
  331. ----------------------
  332. Let's begin by getting the tagged sentence data, and simplifying the tags
  333. as described earlier.
  334. >>> from nltk.corpus import floresta
  335. >>> tsents = floresta.tagged_sents()
  336. >>> tsents = [[(w.lower(),simplify_tag(t)) for (w,t) in sent] for sent in tsents if sent]
  337. >>> train = tsents[100:]
  338. >>> test = tsents[:100]
  339. We already know that ``n`` is the most common tag, so we can set up a
  340. default tagger that tags every word as a noun, and see how well it does:
  341. >>> tagger0 = nltk.DefaultTagger('n')
  342. >>> nltk.tag.accuracy(tagger0, test)
  343. 0.17697228144989338
  344. Evidently, about one in every six words is a noun. Let's improve on this by
  345. training a unigram tagger:
  346. >>> tagger1 = nltk.UnigramTagger(train, backoff=tagger0)
  347. >>> nltk.tag.accuracy(tagger1, test)
  348. 0.87029140014214645
  349. Next a bigram tagger:
  350. >>> tagger2 = nltk.BigramTagger(train, backoff=tagger1)
  351. >>> nltk.tag.accuracy(tagger2, test)
  352. 0.89019189765458417
  353. Sentence Segmentation
  354. ---------------------
  355. Punkt is a language-neutral sentence segmentation tool. We
  356. >>> sent_tokenizer=nltk.data.load('tokenizers/punkt/portuguese.pickle')
  357. >>> raw_text = machado.raw('romance/marm05.txt')
  358. >>> sentences = sent_tokenizer.tokenize(raw_text)
  359. >>> for sent in sentences[1000:1005]:
  360. ... print("<<", sent, ">>")
  361. ...
  362. << Em verdade, parecia ainda mais mulher do que era;
  363. seria criança nos seus folgares de moça; mas assim quieta, impassível, tinha a
  364. compostura da mulher casada. >>
  365. << Talvez essa circunstância lhe diminuía um pouco da
  366. graça virginal. >>
  367. << Depressa nos familiarizamos; a mãe fazia-lhe grandes elogios, eu
  368. escutava-os de boa sombra, e ela sorria com os olhos fúlgidos, como se lá dentro
  369. do cérebro lhe estivesse a voar uma borboletinha de asas de ouro e olhos de
  370. diamante... >>
  371. << Digo lá dentro, porque cá fora o
  372. que esvoaçou foi uma borboleta preta, que subitamente penetrou na varanda, e
  373. começou a bater as asas em derredor de D. Eusébia. >>
  374. << D. Eusébia deu um grito,
  375. levantou-se, praguejou umas palavras soltas: - T'esconjuro!... >>
  376. The sentence tokenizer can be trained and evaluated on other text.
  377. The source text (from the Floresta Portuguese Treebank) contains one sentence per line.
  378. We read the text, split it into its lines, and then join these lines together using
  379. spaces. Now the information about sentence breaks has been discarded. We split this
  380. material into training and testing data:
  381. >>> import os, nltk.test
  382. >>> testdir = os.path.split(nltk.test.__file__)[0]
  383. >>> text = open(os.path.join(testdir, 'floresta.txt'), 'rb').read().decode('ISO-8859-1')
  384. >>> lines = text.split('\n')
  385. >>> train = ' '.join(lines[10:])
  386. >>> test = ' '.join(lines[:10])
  387. Now we train the sentence segmenter (or sentence tokenizer) and use it on our test sentences:
  388. >>> stok = nltk.PunktSentenceTokenizer(train)
  389. >>> print(stok.tokenize(test))
  390. ['O 7 e Meio \xe9 um ex-libris da noite algarvia.',
  391. '\xc9 uma das mais antigas discotecas do Algarve, situada em Albufeira,
  392. que continua a manter os tra\xe7os decorativos e as clientelas de sempre.',
  393. '\xc9 um pouco a vers\xe3o de uma esp\xe9cie de \xaboutro lado\xbb da noite,
  394. a meio caminho entre os devaneios de uma fauna perif\xe9rica, seja de Lisboa,
  395. Londres, Dublin ou Faro e Portim\xe3o, e a postura circunspecta dos fi\xe9is da casa,
  396. que dela esperam a m\xfasica \xabgeracionista\xbb dos 60 ou dos 70.',
  397. 'N\xe3o deixa de ser, nos tempos que correm, um certo \xabvery typical\xbb algarvio,
  398. cabe\xe7a de cartaz para os que querem fugir a algumas movimenta\xe7\xf5es nocturnas
  399. j\xe1 a caminho da ritualiza\xe7\xe3o de massas, do g\xe9nero \xabvamos todos ao
  400. Calypso e encontramo-nos na Locomia\xbb.',
  401. 'E assim, aos 2,5 milh\xf5es que o Minist\xe9rio do Planeamento e Administra\xe7\xe3o
  402. do Territ\xf3rio j\xe1 gasta no pagamento do pessoal afecto a estes organismos,
  403. v\xeam juntar-se os montantes das obras propriamente ditas, que os munic\xedpios,
  404. j\xe1 com projectos na m\xe3o, v\xeam reivindicar junto do Executivo, como salienta
  405. aquele membro do Governo.',
  406. 'E o dinheiro \xabn\xe3o falta s\xf3 \xe0s c\xe2maras\xbb, lembra o secret\xe1rio de Estado,
  407. que considera que a solu\xe7\xe3o para as autarquias \xe9 \xabespecializarem-se em
  408. fundos comunit\xe1rios\xbb.',
  409. 'Mas como, se muitas n\xe3o disp\xf5em, nos seus quadros, dos t\xe9cnicos necess\xe1rios?',
  410. '\xabEncomendem-nos a projectistas de fora\xbb porque, se as obras vierem a ser financiadas,
  411. eles at\xe9 saem de gra\xe7a, j\xe1 que, nesse caso, \xabos fundos comunit\xe1rios pagam
  412. os projectos, o mesmo n\xe3o acontecendo quando eles s\xe3o feitos pelos GAT\xbb,
  413. dado serem organismos do Estado.',
  414. 'Essa poder\xe1 vir a ser uma hip\xf3tese, at\xe9 porque, no terreno, a capacidade dos GAT
  415. est\xe1 cada vez mais enfraquecida.',
  416. 'Alguns at\xe9 j\xe1 desapareceram, como o de Castro Verde, e outros t\xeam vindo a perder quadros.']
  417. NLTK's data collection includes a trained model for Portuguese sentence
  418. segmentation, which can be loaded as follows. It is faster to load a trained model than
  419. to retrain it.
  420. >>> stok = nltk.data.load('tokenizers/punkt/portuguese.pickle')
  421. Stemming
  422. --------
  423. NLTK includes the RSLP Portuguese stemmer. Here we use it to stem some Portuguese text:
  424. >>> stemmer = nltk.stem.RSLPStemmer()
  425. >>> stemmer.stem("copiar")
  426. 'copi'
  427. >>> stemmer.stem("paisagem")
  428. 'pais'
  429. Stopwords
  430. ---------
  431. NLTK includes Portuguese stopwords:
  432. >>> stopwords = nltk.corpus.stopwords.words('portuguese')
  433. >>> stopwords[:10]
  434. ['a', 'ao', 'aos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'at\xe9']
  435. Now we can use these to filter text. Let's find the most frequent words (other than stopwords)
  436. and print them in descending order of frequency:
  437. >>> fd = nltk.FreqDist(w.lower() for w in floresta.words() if w not in stopwords)
  438. >>> for word in list(fd.keys())[:20]:
  439. ... print(word, fd[word])
  440. , 13444
  441. . 7725
  442. « 2369
  443. » 2310
  444. é 1305
  445. o 1086
  446. } 1047
  447. { 1044
  448. a 897
  449. ; 633
  450. em 516
  451. ser 466
  452. sobre 349
  453. os 313
  454. anos 301
  455. ontem 292
  456. ainda 279
  457. segundo 256
  458. ter 249
  459. dois 231