chat80.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. # Natural Language Toolkit: Chat-80 KB Reader
  2. # See http://www.w3.org/TR/swbp-skos-core-guide/
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Author: Ewan Klein <ewan@inf.ed.ac.uk>,
  6. # URL: <http://nltk.sourceforge.net>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Overview
  10. ========
  11. Chat-80 was a natural language system which allowed the user to
  12. interrogate a Prolog knowledge base in the domain of world
  13. geography. It was developed in the early '80s by Warren and Pereira; see
  14. ``http://www.aclweb.org/anthology/J82-3002.pdf`` for a description and
  15. ``http://www.cis.upenn.edu/~pereira/oldies.html`` for the source
  16. files.
  17. This module contains functions to extract data from the Chat-80
  18. relation files ('the world database'), and convert then into a format
  19. that can be incorporated in the FOL models of
  20. ``nltk.sem.evaluate``. The code assumes that the Prolog
  21. input files are available in the NLTK corpora directory.
  22. The Chat-80 World Database consists of the following files::
  23. world0.pl
  24. rivers.pl
  25. cities.pl
  26. countries.pl
  27. contain.pl
  28. borders.pl
  29. This module uses a slightly modified version of ``world0.pl``, in which
  30. a set of Prolog rules have been omitted. The modified file is named
  31. ``world1.pl``. Currently, the file ``rivers.pl`` is not read in, since
  32. it uses a list rather than a string in the second field.
  33. Reading Chat-80 Files
  34. =====================
  35. Chat-80 relations are like tables in a relational database. The
  36. relation acts as the name of the table; the first argument acts as the
  37. 'primary key'; and subsequent arguments are further fields in the
  38. table. In general, the name of the table provides a label for a unary
  39. predicate whose extension is all the primary keys. For example,
  40. relations in ``cities.pl`` are of the following form::
  41. 'city(athens,greece,1368).'
  42. Here, ``'athens'`` is the key, and will be mapped to a member of the
  43. unary predicate *city*.
  44. The fields in the table are mapped to binary predicates. The first
  45. argument of the predicate is the primary key, while the second
  46. argument is the data in the relevant field. Thus, in the above
  47. example, the third field is mapped to the binary predicate
  48. *population_of*, whose extension is a set of pairs such as
  49. ``'(athens, 1368)'``.
  50. An exception to this general framework is required by the relations in
  51. the files ``borders.pl`` and ``contains.pl``. These contain facts of the
  52. following form::
  53. 'borders(albania,greece).'
  54. 'contains0(africa,central_africa).'
  55. We do not want to form a unary concept out the element in
  56. the first field of these records, and we want the label of the binary
  57. relation just to be ``'border'``/``'contain'`` respectively.
  58. In order to drive the extraction process, we use 'relation metadata bundles'
  59. which are Python dictionaries such as the following::
  60. city = {'label': 'city',
  61. 'closures': [],
  62. 'schema': ['city', 'country', 'population'],
  63. 'filename': 'cities.pl'}
  64. According to this, the file ``city['filename']`` contains a list of
  65. relational tuples (or more accurately, the corresponding strings in
  66. Prolog form) whose predicate symbol is ``city['label']`` and whose
  67. relational schema is ``city['schema']``. The notion of a ``closure`` is
  68. discussed in the next section.
  69. Concepts
  70. ========
  71. In order to encapsulate the results of the extraction, a class of
  72. ``Concept`` objects is introduced. A ``Concept`` object has a number of
  73. attributes, in particular a ``prefLabel`` and ``extension``, which make
  74. it easier to inspect the output of the extraction. In addition, the
  75. ``extension`` can be further processed: in the case of the ``'border'``
  76. relation, we check that the relation is symmetric, and in the case
  77. of the ``'contain'`` relation, we carry out the transitive
  78. closure. The closure properties associated with a concept is
  79. indicated in the relation metadata, as indicated earlier.
  80. The ``extension`` of a ``Concept`` object is then incorporated into a
  81. ``Valuation`` object.
  82. Persistence
  83. ===========
  84. The functions ``val_dump`` and ``val_load`` are provided to allow a
  85. valuation to be stored in a persistent database and re-loaded, rather
  86. than having to be re-computed each time.
  87. Individuals and Lexical Items
  88. =============================
  89. As well as deriving relations from the Chat-80 data, we also create a
  90. set of individual constants, one for each entity in the domain. The
  91. individual constants are string-identical to the entities. For
  92. example, given a data item such as ``'zloty'``, we add to the valuation
  93. a pair ``('zloty', 'zloty')``. In order to parse English sentences that
  94. refer to these entities, we also create a lexical item such as the
  95. following for each individual constant::
  96. PropN[num=sg, sem=<\P.(P zloty)>] -> 'Zloty'
  97. The set of rules is written to the file ``chat_pnames.cfg`` in the
  98. current directory.
  99. """
  100. import re
  101. import shelve
  102. import os
  103. import sys
  104. import nltk.data
  105. ###########################################################################
  106. # Chat-80 relation metadata bundles needed to build the valuation
  107. ###########################################################################
  108. borders = {
  109. "rel_name": "borders",
  110. "closures": ["symmetric"],
  111. "schema": ["region", "border"],
  112. "filename": "borders.pl",
  113. }
  114. contains = {
  115. "rel_name": "contains0",
  116. "closures": ["transitive"],
  117. "schema": ["region", "contain"],
  118. "filename": "contain.pl",
  119. }
  120. city = {
  121. "rel_name": "city",
  122. "closures": [],
  123. "schema": ["city", "country", "population"],
  124. "filename": "cities.pl",
  125. }
  126. country = {
  127. "rel_name": "country",
  128. "closures": [],
  129. "schema": [
  130. "country",
  131. "region",
  132. "latitude",
  133. "longitude",
  134. "area",
  135. "population",
  136. "capital",
  137. "currency",
  138. ],
  139. "filename": "countries.pl",
  140. }
  141. circle_of_lat = {
  142. "rel_name": "circle_of_latitude",
  143. "closures": [],
  144. "schema": ["circle_of_latitude", "degrees"],
  145. "filename": "world1.pl",
  146. }
  147. circle_of_long = {
  148. "rel_name": "circle_of_longitude",
  149. "closures": [],
  150. "schema": ["circle_of_longitude", "degrees"],
  151. "filename": "world1.pl",
  152. }
  153. continent = {
  154. "rel_name": "continent",
  155. "closures": [],
  156. "schema": ["continent"],
  157. "filename": "world1.pl",
  158. }
  159. region = {
  160. "rel_name": "in_continent",
  161. "closures": [],
  162. "schema": ["region", "continent"],
  163. "filename": "world1.pl",
  164. }
  165. ocean = {
  166. "rel_name": "ocean",
  167. "closures": [],
  168. "schema": ["ocean"],
  169. "filename": "world1.pl",
  170. }
  171. sea = {"rel_name": "sea", "closures": [], "schema": ["sea"], "filename": "world1.pl"}
  172. items = [
  173. "borders",
  174. "contains",
  175. "city",
  176. "country",
  177. "circle_of_lat",
  178. "circle_of_long",
  179. "continent",
  180. "region",
  181. "ocean",
  182. "sea",
  183. ]
  184. items = tuple(sorted(items))
  185. item_metadata = {
  186. "borders": borders,
  187. "contains": contains,
  188. "city": city,
  189. "country": country,
  190. "circle_of_lat": circle_of_lat,
  191. "circle_of_long": circle_of_long,
  192. "continent": continent,
  193. "region": region,
  194. "ocean": ocean,
  195. "sea": sea,
  196. }
  197. rels = item_metadata.values()
  198. not_unary = ["borders.pl", "contain.pl"]
  199. ###########################################################################
  200. class Concept(object):
  201. """
  202. A Concept class, loosely based on SKOS
  203. (http://www.w3.org/TR/swbp-skos-core-guide/).
  204. """
  205. def __init__(self, prefLabel, arity, altLabels=[], closures=[], extension=set()):
  206. """
  207. :param prefLabel: the preferred label for the concept
  208. :type prefLabel: str
  209. :param arity: the arity of the concept
  210. :type arity: int
  211. @keyword altLabels: other (related) labels
  212. :type altLabels: list
  213. @keyword closures: closure properties of the extension \
  214. (list items can be ``symmetric``, ``reflexive``, ``transitive``)
  215. :type closures: list
  216. @keyword extension: the extensional value of the concept
  217. :type extension: set
  218. """
  219. self.prefLabel = prefLabel
  220. self.arity = arity
  221. self.altLabels = altLabels
  222. self.closures = closures
  223. # keep _extension internally as a set
  224. self._extension = extension
  225. # public access is via a list (for slicing)
  226. self.extension = sorted(list(extension))
  227. def __str__(self):
  228. # _extension = ''
  229. # for element in sorted(self.extension):
  230. # if isinstance(element, tuple):
  231. # element = '(%s, %s)' % (element)
  232. # _extension += element + ', '
  233. # _extension = _extension[:-1]
  234. return "Label = '%s'\nArity = %s\nExtension = %s" % (
  235. self.prefLabel,
  236. self.arity,
  237. self.extension,
  238. )
  239. def __repr__(self):
  240. return "Concept('%s')" % self.prefLabel
  241. def augment(self, data):
  242. """
  243. Add more data to the ``Concept``'s extension set.
  244. :param data: a new semantic value
  245. :type data: string or pair of strings
  246. :rtype: set
  247. """
  248. self._extension.add(data)
  249. self.extension = sorted(list(self._extension))
  250. return self._extension
  251. def _make_graph(self, s):
  252. """
  253. Convert a set of pairs into an adjacency linked list encoding of a graph.
  254. """
  255. g = {}
  256. for (x, y) in s:
  257. if x in g:
  258. g[x].append(y)
  259. else:
  260. g[x] = [y]
  261. return g
  262. def _transclose(self, g):
  263. """
  264. Compute the transitive closure of a graph represented as a linked list.
  265. """
  266. for x in g:
  267. for adjacent in g[x]:
  268. # check that adjacent is a key
  269. if adjacent in g:
  270. for y in g[adjacent]:
  271. if y not in g[x]:
  272. g[x].append(y)
  273. return g
  274. def _make_pairs(self, g):
  275. """
  276. Convert an adjacency linked list back into a set of pairs.
  277. """
  278. pairs = []
  279. for node in g:
  280. for adjacent in g[node]:
  281. pairs.append((node, adjacent))
  282. return set(pairs)
  283. def close(self):
  284. """
  285. Close a binary relation in the ``Concept``'s extension set.
  286. :return: a new extension for the ``Concept`` in which the
  287. relation is closed under a given property
  288. """
  289. from nltk.sem import is_rel
  290. assert is_rel(self._extension)
  291. if "symmetric" in self.closures:
  292. pairs = []
  293. for (x, y) in self._extension:
  294. pairs.append((y, x))
  295. sym = set(pairs)
  296. self._extension = self._extension.union(sym)
  297. if "transitive" in self.closures:
  298. all = self._make_graph(self._extension)
  299. closed = self._transclose(all)
  300. trans = self._make_pairs(closed)
  301. self._extension = self._extension.union(trans)
  302. self.extension = sorted(list(self._extension))
  303. def clause2concepts(filename, rel_name, schema, closures=[]):
  304. """
  305. Convert a file of Prolog clauses into a list of ``Concept`` objects.
  306. :param filename: filename containing the relations
  307. :type filename: str
  308. :param rel_name: name of the relation
  309. :type rel_name: str
  310. :param schema: the schema used in a set of relational tuples
  311. :type schema: list
  312. :param closures: closure properties for the extension of the concept
  313. :type closures: list
  314. :return: a list of ``Concept`` objects
  315. :rtype: list
  316. """
  317. concepts = []
  318. # position of the subject of a binary relation
  319. subj = 0
  320. # label of the 'primary key'
  321. pkey = schema[0]
  322. # fields other than the primary key
  323. fields = schema[1:]
  324. # convert a file into a list of lists
  325. records = _str2records(filename, rel_name)
  326. # add a unary concept corresponding to the set of entities
  327. # in the primary key position
  328. # relations in 'not_unary' are more like ordinary binary relations
  329. if not filename in not_unary:
  330. concepts.append(unary_concept(pkey, subj, records))
  331. # add a binary concept for each non-key field
  332. for field in fields:
  333. obj = schema.index(field)
  334. concepts.append(binary_concept(field, closures, subj, obj, records))
  335. return concepts
  336. def cities2table(filename, rel_name, dbname, verbose=False, setup=False):
  337. """
  338. Convert a file of Prolog clauses into a database table.
  339. This is not generic, since it doesn't allow arbitrary
  340. schemas to be set as a parameter.
  341. Intended usage::
  342. cities2table('cities.pl', 'city', 'city.db', verbose=True, setup=True)
  343. :param filename: filename containing the relations
  344. :type filename: str
  345. :param rel_name: name of the relation
  346. :type rel_name: str
  347. :param dbname: filename of persistent store
  348. :type schema: str
  349. """
  350. import sqlite3
  351. records = _str2records(filename, rel_name)
  352. connection = sqlite3.connect(dbname)
  353. cur = connection.cursor()
  354. if setup:
  355. cur.execute(
  356. """CREATE TABLE city_table
  357. (City text, Country text, Population int)"""
  358. )
  359. table_name = "city_table"
  360. for t in records:
  361. cur.execute("insert into %s values (?,?,?)" % table_name, t)
  362. if verbose:
  363. print("inserting values into %s: " % table_name, t)
  364. connection.commit()
  365. if verbose:
  366. print("Committing update to %s" % dbname)
  367. cur.close()
  368. def sql_query(dbname, query):
  369. """
  370. Execute an SQL query over a database.
  371. :param dbname: filename of persistent store
  372. :type schema: str
  373. :param query: SQL query
  374. :type rel_name: str
  375. """
  376. import sqlite3
  377. try:
  378. path = nltk.data.find(dbname)
  379. connection = sqlite3.connect(str(path))
  380. cur = connection.cursor()
  381. return cur.execute(query)
  382. except (ValueError, sqlite3.OperationalError):
  383. import warnings
  384. warnings.warn(
  385. "Make sure the database file %s is installed and uncompressed." % dbname
  386. )
  387. raise
  388. def _str2records(filename, rel):
  389. """
  390. Read a file into memory and convert each relation clause into a list.
  391. """
  392. recs = []
  393. contents = nltk.data.load("corpora/chat80/%s" % filename, format="text")
  394. for line in contents.splitlines():
  395. if line.startswith(rel):
  396. line = re.sub(rel + r"\(", "", line)
  397. line = re.sub(r"\)\.$", "", line)
  398. record = line.split(",")
  399. recs.append(record)
  400. return recs
  401. def unary_concept(label, subj, records):
  402. """
  403. Make a unary concept out of the primary key in a record.
  404. A record is a list of entities in some relation, such as
  405. ``['france', 'paris']``, where ``'france'`` is acting as the primary
  406. key.
  407. :param label: the preferred label for the concept
  408. :type label: string
  409. :param subj: position in the record of the subject of the predicate
  410. :type subj: int
  411. :param records: a list of records
  412. :type records: list of lists
  413. :return: ``Concept`` of arity 1
  414. :rtype: Concept
  415. """
  416. c = Concept(label, arity=1, extension=set())
  417. for record in records:
  418. c.augment(record[subj])
  419. return c
  420. def binary_concept(label, closures, subj, obj, records):
  421. """
  422. Make a binary concept out of the primary key and another field in a record.
  423. A record is a list of entities in some relation, such as
  424. ``['france', 'paris']``, where ``'france'`` is acting as the primary
  425. key, and ``'paris'`` stands in the ``'capital_of'`` relation to
  426. ``'france'``.
  427. More generally, given a record such as ``['a', 'b', 'c']``, where
  428. label is bound to ``'B'``, and ``obj`` bound to 1, the derived
  429. binary concept will have label ``'B_of'``, and its extension will
  430. be a set of pairs such as ``('a', 'b')``.
  431. :param label: the base part of the preferred label for the concept
  432. :type label: str
  433. :param closures: closure properties for the extension of the concept
  434. :type closures: list
  435. :param subj: position in the record of the subject of the predicate
  436. :type subj: int
  437. :param obj: position in the record of the object of the predicate
  438. :type obj: int
  439. :param records: a list of records
  440. :type records: list of lists
  441. :return: ``Concept`` of arity 2
  442. :rtype: Concept
  443. """
  444. if not label == "border" and not label == "contain":
  445. label = label + "_of"
  446. c = Concept(label, arity=2, closures=closures, extension=set())
  447. for record in records:
  448. c.augment((record[subj], record[obj]))
  449. # close the concept's extension according to the properties in closures
  450. c.close()
  451. return c
  452. def process_bundle(rels):
  453. """
  454. Given a list of relation metadata bundles, make a corresponding
  455. dictionary of concepts, indexed by the relation name.
  456. :param rels: bundle of metadata needed for constructing a concept
  457. :type rels: list(dict)
  458. :return: a dictionary of concepts, indexed by the relation name.
  459. :rtype: dict(str): Concept
  460. """
  461. concepts = {}
  462. for rel in rels:
  463. rel_name = rel["rel_name"]
  464. closures = rel["closures"]
  465. schema = rel["schema"]
  466. filename = rel["filename"]
  467. concept_list = clause2concepts(filename, rel_name, schema, closures)
  468. for c in concept_list:
  469. label = c.prefLabel
  470. if label in concepts:
  471. for data in c.extension:
  472. concepts[label].augment(data)
  473. concepts[label].close()
  474. else:
  475. concepts[label] = c
  476. return concepts
  477. def make_valuation(concepts, read=False, lexicon=False):
  478. """
  479. Convert a list of ``Concept`` objects into a list of (label, extension) pairs;
  480. optionally create a ``Valuation`` object.
  481. :param concepts: concepts
  482. :type concepts: list(Concept)
  483. :param read: if ``True``, ``(symbol, set)`` pairs are read into a ``Valuation``
  484. :type read: bool
  485. :rtype: list or Valuation
  486. """
  487. vals = []
  488. for c in concepts:
  489. vals.append((c.prefLabel, c.extension))
  490. if lexicon:
  491. read = True
  492. if read:
  493. from nltk.sem import Valuation
  494. val = Valuation({})
  495. val.update(vals)
  496. # add labels for individuals
  497. val = label_indivs(val, lexicon=lexicon)
  498. return val
  499. else:
  500. return vals
  501. def val_dump(rels, db):
  502. """
  503. Make a ``Valuation`` from a list of relation metadata bundles and dump to
  504. persistent database.
  505. :param rels: bundle of metadata needed for constructing a concept
  506. :type rels: list of dict
  507. :param db: name of file to which data is written.
  508. The suffix '.db' will be automatically appended.
  509. :type db: str
  510. """
  511. concepts = process_bundle(rels).values()
  512. valuation = make_valuation(concepts, read=True)
  513. db_out = shelve.open(db, "n")
  514. db_out.update(valuation)
  515. db_out.close()
  516. def val_load(db):
  517. """
  518. Load a ``Valuation`` from a persistent database.
  519. :param db: name of file from which data is read.
  520. The suffix '.db' should be omitted from the name.
  521. :type db: str
  522. """
  523. dbname = db + ".db"
  524. if not os.access(dbname, os.R_OK):
  525. sys.exit("Cannot read file: %s" % dbname)
  526. else:
  527. db_in = shelve.open(db)
  528. from nltk.sem import Valuation
  529. val = Valuation(db_in)
  530. # val.read(db_in.items())
  531. return val
  532. # def alpha(str):
  533. # """
  534. # Utility to filter out non-alphabetic constants.
  535. #:param str: candidate constant
  536. #:type str: string
  537. #:rtype: bool
  538. # """
  539. # try:
  540. # int(str)
  541. # return False
  542. # except ValueError:
  543. ## some unknown values in records are labeled '?'
  544. # if not str == '?':
  545. # return True
  546. def label_indivs(valuation, lexicon=False):
  547. """
  548. Assign individual constants to the individuals in the domain of a ``Valuation``.
  549. Given a valuation with an entry of the form ``{'rel': {'a': True}}``,
  550. add a new entry ``{'a': 'a'}``.
  551. :type valuation: Valuation
  552. :rtype: Valuation
  553. """
  554. # collect all the individuals into a domain
  555. domain = valuation.domain
  556. # convert the domain into a sorted list of alphabetic terms
  557. # use the same string as a label
  558. pairs = [(e, e) for e in domain]
  559. if lexicon:
  560. lex = make_lex(domain)
  561. with open("chat_pnames.cfg", "w") as outfile:
  562. outfile.writelines(lex)
  563. # read the pairs into the valuation
  564. valuation.update(pairs)
  565. return valuation
  566. def make_lex(symbols):
  567. """
  568. Create lexical CFG rules for each individual symbol.
  569. Given a valuation with an entry of the form ``{'zloty': 'zloty'}``,
  570. create a lexical rule for the proper name 'Zloty'.
  571. :param symbols: a list of individual constants in the semantic representation
  572. :type symbols: sequence -- set(str)
  573. :rtype: list(str)
  574. """
  575. lex = []
  576. header = """
  577. ##################################################################
  578. # Lexical rules automatically generated by running 'chat80.py -x'.
  579. ##################################################################
  580. """
  581. lex.append(header)
  582. template = "PropN[num=sg, sem=<\P.(P %s)>] -> '%s'\n"
  583. for s in symbols:
  584. parts = s.split("_")
  585. caps = [p.capitalize() for p in parts]
  586. pname = "_".join(caps)
  587. rule = template % (s, pname)
  588. lex.append(rule)
  589. return lex
  590. ###########################################################################
  591. # Interface function to emulate other corpus readers
  592. ###########################################################################
  593. def concepts(items=items):
  594. """
  595. Build a list of concepts corresponding to the relation names in ``items``.
  596. :param items: names of the Chat-80 relations to extract
  597. :type items: list(str)
  598. :return: the ``Concept`` objects which are extracted from the relations
  599. :rtype: list(Concept)
  600. """
  601. if isinstance(items, str):
  602. items = (items,)
  603. rels = [item_metadata[r] for r in items]
  604. concept_map = process_bundle(rels)
  605. return concept_map.values()
  606. ###########################################################################
  607. def main():
  608. import sys
  609. from optparse import OptionParser
  610. description = """
  611. Extract data from the Chat-80 Prolog files and convert them into a
  612. Valuation object for use in the NLTK semantics package.
  613. """
  614. opts = OptionParser(description=description)
  615. opts.set_defaults(verbose=True, lex=False, vocab=False)
  616. opts.add_option(
  617. "-s", "--store", dest="outdb", help="store a valuation in DB", metavar="DB"
  618. )
  619. opts.add_option(
  620. "-l",
  621. "--load",
  622. dest="indb",
  623. help="load a stored valuation from DB",
  624. metavar="DB",
  625. )
  626. opts.add_option(
  627. "-c",
  628. "--concepts",
  629. action="store_true",
  630. help="print concepts instead of a valuation",
  631. )
  632. opts.add_option(
  633. "-r",
  634. "--relation",
  635. dest="label",
  636. help="print concept with label REL (check possible labels with '-v' option)",
  637. metavar="REL",
  638. )
  639. opts.add_option(
  640. "-q",
  641. "--quiet",
  642. action="store_false",
  643. dest="verbose",
  644. help="don't print out progress info",
  645. )
  646. opts.add_option(
  647. "-x",
  648. "--lex",
  649. action="store_true",
  650. dest="lex",
  651. help="write a file of lexical entries for country names, then exit",
  652. )
  653. opts.add_option(
  654. "-v",
  655. "--vocab",
  656. action="store_true",
  657. dest="vocab",
  658. help="print out the vocabulary of concept labels and their arity, then exit",
  659. )
  660. (options, args) = opts.parse_args()
  661. if options.outdb and options.indb:
  662. opts.error("Options --store and --load are mutually exclusive")
  663. if options.outdb:
  664. # write the valuation to a persistent database
  665. if options.verbose:
  666. outdb = options.outdb + ".db"
  667. print("Dumping a valuation to %s" % outdb)
  668. val_dump(rels, options.outdb)
  669. sys.exit(0)
  670. else:
  671. # try to read in a valuation from a database
  672. if options.indb is not None:
  673. dbname = options.indb + ".db"
  674. if not os.access(dbname, os.R_OK):
  675. sys.exit("Cannot read file: %s" % dbname)
  676. else:
  677. valuation = val_load(options.indb)
  678. # we need to create the valuation from scratch
  679. else:
  680. # build some concepts
  681. concept_map = process_bundle(rels)
  682. concepts = concept_map.values()
  683. # just print out the vocabulary
  684. if options.vocab:
  685. items = sorted([(c.arity, c.prefLabel) for c in concepts])
  686. for (arity, label) in items:
  687. print(label, arity)
  688. sys.exit(0)
  689. # show all the concepts
  690. if options.concepts:
  691. for c in concepts:
  692. print(c)
  693. print()
  694. if options.label:
  695. print(concept_map[options.label])
  696. sys.exit(0)
  697. else:
  698. # turn the concepts into a Valuation
  699. if options.lex:
  700. if options.verbose:
  701. print("Writing out lexical rules")
  702. make_valuation(concepts, lexicon=True)
  703. else:
  704. valuation = make_valuation(concepts, read=True)
  705. print(valuation)
  706. def sql_demo():
  707. """
  708. Print out every row from the 'city.db' database.
  709. """
  710. print()
  711. print("Using SQL to extract rows from 'city.db' RDB.")
  712. for row in sql_query("corpora/city_database/city.db", "SELECT * FROM city_table"):
  713. print(row)
  714. if __name__ == "__main__":
  715. main()
  716. sql_demo()