URI: 
       vt.py - vt - Print definitions from Vocabolario Treccani
  HTML hg clone https://bitbucket.org/iamleot/vt
   DIR Log
   DIR Files
   DIR Refs
   DIR README
       ---
       vt.py
       ---
            1 #!/usr/pkg/bin/python3.7
            2 
            3 #
            4 # Copyright (c) 2017-2019 Leonardo Taccari
            5 # All rights reserved.
            6 # 
            7 # Redistribution and use in source and binary forms, with or without
            8 # modification, are permitted provided that the following conditions
            9 # are met:
           10 # 
           11 # 1. Redistributions of source code must retain the above copyright
           12 #    notice, this list of conditions and the following disclaimer.
           13 # 2. Redistributions in binary form must reproduce the above copyright
           14 #    notice, this list of conditions and the following disclaimer in the
           15 #    documentation and/or other materials provided with the distribution.
           16 # 
           17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
           18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
           19 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
           20 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
           21 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
           22 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
           23 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
           24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
           25 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
           26 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
           27 # POSSIBILITY OF SUCH DAMAGE.
           28 #
           29 
           30 
           31 """
           32 print definition from Vocabolario Treccani
           33 
           34 vt is a Python script/module to print the definition of a term using
           35 Vocabolario Treccani (<http://www.treccani.it/vocabolario/>).
           36 """
           37 
           38 
           39 from urllib import parse, request
           40 import textwrap
           41 
           42 from bs4 import BeautifulSoup, SoupStrainer
           43 
           44 
           45 def lookup_term(term, html=False):
           46     """Lookup a term in the Treccani's Vocabolario
           47 
           48     Given a term try to search it in Vocabolario Treccani.
           49     Accept an optional html boolean flag to avoid converting to text.
           50 
           51     Returns the relevant text output of the term or None if nothing relevant
           52     was found.
           53 
           54     >>> lookup_term('birbante')
           55     'birbante s. m. [der. di birba1]. – Uomo che conduce vita poco onesta, scaltro e insieme malvagio. Spesso detto per scherzo o per affettuoso rimprovero (anche di o a ragazzi) per denotare soprattutto furberia, impertinenza e sim., e con questo sign. estens. è usato anche al femm.: quante me ne combina, quel b. di tuo nipote; quel b. me l’ha fatta; ah, b., t’ho colto finalmente!; quella b. della tua segretaria m’ha detto che non eri in ufficio! ◆ Dim. scherz. birbantèllo (anche al femm., birbantèlla); accr. scherz. birbantàccio.'
           56     """
           57     url = 'http://www.treccani.it/vocabolario/' + parse.quote(term)
           58 
           59     with request.urlopen(url) as r:
           60         t = BeautifulSoup(r, 'html.parser',
           61                           parse_only=SoupStrainer(class_='text spiega'))
           62 
           63     res = t.p if t.p else None
           64     if res and not html:
           65         res = res.text.strip()
           66 
           67     return res
           68 
           69 
           70 def terms(term, html=False):
           71     """Return a list of terms in the Treccani's Vocabolario
           72 
           73     Given a term return a list of zero or more definition regarding the
           74     term.
           75 
           76     Accept an optional html boolean flag to avoid converting to text.
           77 
           78     >>> terms('birba')
           79     ['birba1 s. f. [etimo incerto]. – Persona priva di scrupoli, cattivo soggetto (sinon., quindi, del più com. birbante): Vostra Eccellenza, che ... mi gabella per anti-tedesco Perché metto le b. alla berlina (Giusti); credeva senza dubbio d’aver da fare con una b. matricolata (Pirandello). Più spesso, con tono scherz., bambino, ragazzino furbo, vispo, impertinente e malizioso: quella b. di mio figlio. Anticam. ebbe anche sign. astratto di malizia, frode, in varie locuz. furbesche. ◆ Dim. scherz. birbétta, birberèlla, birbacchiòlo m. e birbacchiòla f., pegg. birbàccia e più com. birbaccióne m. e birbaccióna f.; v. anche birbone, che è propr. accr. di birba ma è sentito ormai come voce a sé.', 'birba2 s. f. [etimo incerto], region. ant. – Carrozza scoperta a due posti, tirata da due cavalli: Signore, come gli dissi, io son venuto in birba ... E sono venuto con due cavalli (Goldoni).']
           80     """
           81     ts = []
           82 
           83     t = lookup_term(term, html)
           84     if t:
           85         ts.append(t)
           86     else:
           87         i = 1
           88         while True:
           89             t = lookup_term(term + str(i))
           90             if not t:
           91                 break
           92             ts.append(t)
           93             i += 1
           94 
           95     return ts
           96 
           97 
           98 def print_term(term):
           99     """Pretty print a definition"""
          100     print(textwrap.fill(term, width=80, break_long_words=False,
          101                         break_on_hyphens=False).strip())
          102 
          103 
          104 if __name__ == '__main__':
          105     import sys
          106 
          107     def usage():
          108         print('usage: {} term'.format(sys.argv[0]))
          109         sys.exit(1)
          110 
          111     if len(sys.argv) != 2:
          112         usage()
          113 
          114     term = sys.argv[1]
          115 
          116     for i, t in enumerate(terms(term)):
          117         if i > 0:
          118             print()
          119         print_term(t)