internals.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. # Natural Language Toolkit: Internal utility functions
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Steven Bird <stevenbird1@gmail.com>
  5. # Edward Loper <edloper@gmail.com>
  6. # Nitin Madnani <nmadnani@ets.org>
  7. # URL: <http://nltk.org/>
  8. # For license information, see LICENSE.TXT
  9. import subprocess
  10. import os
  11. import fnmatch
  12. import re
  13. import warnings
  14. import textwrap
  15. import types
  16. import sys
  17. import stat
  18. import locale
  19. from xml.etree import ElementTree
  20. ##########################################################################
  21. # Java Via Command-Line
  22. ##########################################################################
  23. _java_bin = None
  24. _java_options = []
  25. # [xx] add classpath option to config_java?
  26. def config_java(bin=None, options=None, verbose=False):
  27. """
  28. Configure nltk's java interface, by letting nltk know where it can
  29. find the Java binary, and what extra options (if any) should be
  30. passed to Java when it is run.
  31. :param bin: The full path to the Java binary. If not specified,
  32. then nltk will search the system for a Java binary; and if
  33. one is not found, it will raise a ``LookupError`` exception.
  34. :type bin: str
  35. :param options: A list of options that should be passed to the
  36. Java binary when it is called. A common value is
  37. ``'-Xmx512m'``, which tells Java binary to increase
  38. the maximum heap size to 512 megabytes. If no options are
  39. specified, then do not modify the options list.
  40. :type options: list(str)
  41. """
  42. global _java_bin, _java_options
  43. _java_bin = find_binary(
  44. "java",
  45. bin,
  46. env_vars=["JAVAHOME", "JAVA_HOME"],
  47. verbose=verbose,
  48. binary_names=["java.exe"],
  49. )
  50. if options is not None:
  51. if isinstance(options, str):
  52. options = options.split()
  53. _java_options = list(options)
  54. def java(cmd, classpath=None, stdin=None, stdout=None, stderr=None, blocking=True):
  55. """
  56. Execute the given java command, by opening a subprocess that calls
  57. Java. If java has not yet been configured, it will be configured
  58. by calling ``config_java()`` with no arguments.
  59. :param cmd: The java command that should be called, formatted as
  60. a list of strings. Typically, the first string will be the name
  61. of the java class; and the remaining strings will be arguments
  62. for that java class.
  63. :type cmd: list(str)
  64. :param classpath: A ``':'`` separated list of directories, JAR
  65. archives, and ZIP archives to search for class files.
  66. :type classpath: str
  67. :param stdin, stdout, stderr: Specify the executed programs'
  68. standard input, standard output and standard error file
  69. handles, respectively. Valid values are ``subprocess.PIPE``,
  70. an existing file descriptor (a positive integer), an existing
  71. file object, 'pipe', 'stdout', 'devnull' and None. ``subprocess.PIPE`` indicates that a
  72. new pipe to the child should be created. With None, no
  73. redirection will occur; the child's file handles will be
  74. inherited from the parent. Additionally, stderr can be
  75. ``subprocess.STDOUT``, which indicates that the stderr data
  76. from the applications should be captured into the same file
  77. handle as for stdout.
  78. :param blocking: If ``false``, then return immediately after
  79. spawning the subprocess. In this case, the return value is
  80. the ``Popen`` object, and not a ``(stdout, stderr)`` tuple.
  81. :return: If ``blocking=True``, then return a tuple ``(stdout,
  82. stderr)``, containing the stdout and stderr outputs generated
  83. by the java command if the ``stdout`` and ``stderr`` parameters
  84. were set to ``subprocess.PIPE``; or None otherwise. If
  85. ``blocking=False``, then return a ``subprocess.Popen`` object.
  86. :raise OSError: If the java command returns a nonzero return code.
  87. """
  88. subprocess_output_dict = {
  89. "pipe": subprocess.PIPE,
  90. "stdout": subprocess.STDOUT,
  91. "devnull": subprocess.DEVNULL,
  92. }
  93. stdin = subprocess_output_dict.get(stdin, stdin)
  94. stdout = subprocess_output_dict.get(stdout, stdout)
  95. stderr = subprocess_output_dict.get(stderr, stderr)
  96. if isinstance(cmd, str):
  97. raise TypeError("cmd should be a list of strings")
  98. # Make sure we know where a java binary is.
  99. if _java_bin is None:
  100. config_java()
  101. # Set up the classpath.
  102. if isinstance(classpath, str):
  103. classpaths = [classpath]
  104. else:
  105. classpaths = list(classpath)
  106. classpath = os.path.pathsep.join(classpaths)
  107. # Construct the full command string.
  108. cmd = list(cmd)
  109. cmd = ["-cp", classpath] + cmd
  110. cmd = [_java_bin] + _java_options + cmd
  111. # Call java via a subprocess
  112. p = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr)
  113. if not blocking:
  114. return p
  115. (stdout, stderr) = p.communicate()
  116. # Check the return code.
  117. if p.returncode != 0:
  118. print(_decode_stdoutdata(stderr))
  119. raise OSError("Java command failed : " + str(cmd))
  120. return (stdout, stderr)
  121. if 0:
  122. # config_java(options='-Xmx512m')
  123. # Write:
  124. # java('weka.classifiers.bayes.NaiveBayes',
  125. # ['-d', '/tmp/names.model', '-t', '/tmp/train.arff'],
  126. # classpath='/Users/edloper/Desktop/weka/weka.jar')
  127. # Read:
  128. (a, b) = java(
  129. [
  130. "weka.classifiers.bayes.NaiveBayes",
  131. "-l",
  132. "/tmp/names.model",
  133. "-T",
  134. "/tmp/test.arff",
  135. "-p",
  136. "0",
  137. ], # , '-distribution'],
  138. classpath="/Users/edloper/Desktop/weka/weka.jar",
  139. )
  140. ######################################################################
  141. # Parsing
  142. ######################################################################
  143. class ReadError(ValueError):
  144. """
  145. Exception raised by read_* functions when they fail.
  146. :param position: The index in the input string where an error occurred.
  147. :param expected: What was expected when an error occurred.
  148. """
  149. def __init__(self, expected, position):
  150. ValueError.__init__(self, expected, position)
  151. self.expected = expected
  152. self.position = position
  153. def __str__(self):
  154. return "Expected %s at %s" % (self.expected, self.position)
  155. _STRING_START_RE = re.compile(r"[uU]?[rR]?(\"\"\"|\'\'\'|\"|\')")
  156. def read_str(s, start_position):
  157. """
  158. If a Python string literal begins at the specified position in the
  159. given string, then return a tuple ``(val, end_position)``
  160. containing the value of the string literal and the position where
  161. it ends. Otherwise, raise a ``ReadError``.
  162. :param s: A string that will be checked to see if within which a
  163. Python string literal exists.
  164. :type s: str
  165. :param start_position: The specified beginning position of the string ``s``
  166. to begin regex matching.
  167. :type start_position: int
  168. :return: A tuple containing the matched string literal evaluated as a
  169. string and the end position of the string literal.
  170. :rtype: tuple(str, int)
  171. :raise ReadError: If the ``_STRING_START_RE`` regex doesn't return a
  172. match in ``s`` at ``start_position``, i.e., open quote. If the
  173. ``_STRING_END_RE`` regex doesn't return a match in ``s`` at the
  174. end of the first match, i.e., close quote.
  175. :raise ValueError: If an invalid string (i.e., contains an invalid
  176. escape sequence) is passed into the ``eval``.
  177. :Example:
  178. >>> from nltk.internals import read_str
  179. >>> read_str('"Hello", World!', 0)
  180. ('Hello', 7)
  181. """
  182. # Read the open quote, and any modifiers.
  183. m = _STRING_START_RE.match(s, start_position)
  184. if not m:
  185. raise ReadError("open quote", start_position)
  186. quotemark = m.group(1)
  187. # Find the close quote.
  188. _STRING_END_RE = re.compile(r"\\|%s" % quotemark)
  189. position = m.end()
  190. while True:
  191. match = _STRING_END_RE.search(s, position)
  192. if not match:
  193. raise ReadError("close quote", position)
  194. if match.group(0) == "\\":
  195. position = match.end() + 1
  196. else:
  197. break
  198. # Process it, using eval. Strings with invalid escape sequences
  199. # might raise ValueEerror.
  200. try:
  201. return eval(s[start_position : match.end()]), match.end()
  202. except ValueError as e:
  203. raise ReadError("invalid string (%s)" % e)
  204. _READ_INT_RE = re.compile(r"-?\d+")
  205. def read_int(s, start_position):
  206. """
  207. If an integer begins at the specified position in the given
  208. string, then return a tuple ``(val, end_position)`` containing the
  209. value of the integer and the position where it ends. Otherwise,
  210. raise a ``ReadError``.
  211. :param s: A string that will be checked to see if within which a
  212. Python integer exists.
  213. :type s: str
  214. :param start_position: The specified beginning position of the string ``s``
  215. to begin regex matching.
  216. :type start_position: int
  217. :return: A tuple containing the matched integer casted to an int,
  218. and the end position of the int in ``s``.
  219. :rtype: tuple(int, int)
  220. :raise ReadError: If the ``_READ_INT_RE`` regex doesn't return a
  221. match in ``s`` at ``start_position``.
  222. :Example:
  223. >>> from nltk.internals import read_int
  224. >>> read_int('42 is the answer', 0)
  225. (42, 2)
  226. """
  227. m = _READ_INT_RE.match(s, start_position)
  228. if not m:
  229. raise ReadError("integer", start_position)
  230. return int(m.group()), m.end()
  231. _READ_NUMBER_VALUE = re.compile(r"-?(\d*)([.]?\d*)?")
  232. def read_number(s, start_position):
  233. """
  234. If an integer or float begins at the specified position in the
  235. given string, then return a tuple ``(val, end_position)``
  236. containing the value of the number and the position where it ends.
  237. Otherwise, raise a ``ReadError``.
  238. :param s: A string that will be checked to see if within which a
  239. Python number exists.
  240. :type s: str
  241. :param start_position: The specified beginning position of the string ``s``
  242. to begin regex matching.
  243. :type start_position: int
  244. :return: A tuple containing the matched number casted to a ``float``,
  245. and the end position of the number in ``s``.
  246. :rtype: tuple(float, int)
  247. :raise ReadError: If the ``_READ_NUMBER_VALUE`` regex doesn't return a
  248. match in ``s`` at ``start_position``.
  249. :Example:
  250. >>> from nltk.internals import read_number
  251. >>> read_number('Pi is 3.14159', 6)
  252. (3.14159, 13)
  253. """
  254. m = _READ_NUMBER_VALUE.match(s, start_position)
  255. if not m or not (m.group(1) or m.group(2)):
  256. raise ReadError("number", start_position)
  257. if m.group(2):
  258. return float(m.group()), m.end()
  259. else:
  260. return int(m.group()), m.end()
  261. ######################################################################
  262. # Check if a method has been overridden
  263. ######################################################################
  264. def overridden(method):
  265. """
  266. :return: True if ``method`` overrides some method with the same
  267. name in a base class. This is typically used when defining
  268. abstract base classes or interfaces, to allow subclasses to define
  269. either of two related methods:
  270. >>> class EaterI:
  271. ... '''Subclass must define eat() or batch_eat().'''
  272. ... def eat(self, food):
  273. ... if overridden(self.batch_eat):
  274. ... return self.batch_eat([food])[0]
  275. ... else:
  276. ... raise NotImplementedError()
  277. ... def batch_eat(self, foods):
  278. ... return [self.eat(food) for food in foods]
  279. :type method: instance method
  280. """
  281. if isinstance(method, types.MethodType) and method.__self__.__class__ is not None:
  282. name = method.__name__
  283. funcs = [
  284. cls.__dict__[name]
  285. for cls in _mro(method.__self__.__class__)
  286. if name in cls.__dict__
  287. ]
  288. return len(funcs) > 1
  289. else:
  290. raise TypeError("Expected an instance method.")
  291. def _mro(cls):
  292. """
  293. Return the method resolution order for ``cls`` -- i.e., a list
  294. containing ``cls`` and all its base classes, in the order in which
  295. they would be checked by ``getattr``. For new-style classes, this
  296. is just cls.__mro__. For classic classes, this can be obtained by
  297. a depth-first left-to-right traversal of ``__bases__``.
  298. """
  299. if isinstance(cls, type):
  300. return cls.__mro__
  301. else:
  302. mro = [cls]
  303. for base in cls.__bases__:
  304. mro.extend(_mro(base))
  305. return mro
  306. ######################################################################
  307. # Deprecation decorator & base class
  308. ######################################################################
  309. # [xx] dedent msg first if it comes from a docstring.
  310. def _add_epytext_field(obj, field, message):
  311. """Add an epytext @field to a given object's docstring."""
  312. indent = ""
  313. # If we already have a docstring, then add a blank line to separate
  314. # it from the new field, and check its indentation.
  315. if obj.__doc__:
  316. obj.__doc__ = obj.__doc__.rstrip() + "\n\n"
  317. indents = re.findall(r"(?<=\n)[ ]+(?!\s)", obj.__doc__.expandtabs())
  318. if indents:
  319. indent = min(indents)
  320. # If we don't have a docstring, add an empty one.
  321. else:
  322. obj.__doc__ = ""
  323. obj.__doc__ += textwrap.fill(
  324. "@%s: %s" % (field, message),
  325. initial_indent=indent,
  326. subsequent_indent=indent + " ",
  327. )
  328. def deprecated(message):
  329. """
  330. A decorator used to mark functions as deprecated. This will cause
  331. a warning to be printed the when the function is used. Usage:
  332. >>> from nltk.internals import deprecated
  333. >>> @deprecated('Use foo() instead')
  334. ... def bar(x):
  335. ... print(x/10)
  336. """
  337. def decorator(func):
  338. msg = "Function %s() has been deprecated. %s" % (func.__name__, message)
  339. msg = "\n" + textwrap.fill(msg, initial_indent=" ", subsequent_indent=" ")
  340. def newFunc(*args, **kwargs):
  341. warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
  342. return func(*args, **kwargs)
  343. # Copy the old function's name, docstring, & dict
  344. newFunc.__dict__.update(func.__dict__)
  345. newFunc.__name__ = func.__name__
  346. newFunc.__doc__ = func.__doc__
  347. newFunc.__deprecated__ = True
  348. # Add a @deprecated field to the docstring.
  349. _add_epytext_field(newFunc, "deprecated", message)
  350. return newFunc
  351. return decorator
  352. class Deprecated(object):
  353. """
  354. A base class used to mark deprecated classes. A typical usage is to
  355. alert users that the name of a class has changed:
  356. >>> from nltk.internals import Deprecated
  357. >>> class NewClassName(object):
  358. ... pass # All logic goes here.
  359. ...
  360. >>> class OldClassName(Deprecated, NewClassName):
  361. ... "Use NewClassName instead."
  362. The docstring of the deprecated class will be used in the
  363. deprecation warning message.
  364. """
  365. def __new__(cls, *args, **kwargs):
  366. # Figure out which class is the deprecated one.
  367. dep_cls = None
  368. for base in _mro(cls):
  369. if Deprecated in base.__bases__:
  370. dep_cls = base
  371. break
  372. assert dep_cls, "Unable to determine which base is deprecated."
  373. # Construct an appropriate warning.
  374. doc = dep_cls.__doc__ or "".strip()
  375. # If there's a @deprecated field, strip off the field marker.
  376. doc = re.sub(r"\A\s*@deprecated:", r"", doc)
  377. # Strip off any indentation.
  378. doc = re.sub(r"(?m)^\s*", "", doc)
  379. # Construct a 'name' string.
  380. name = "Class %s" % dep_cls.__name__
  381. if cls != dep_cls:
  382. name += " (base class for %s)" % cls.__name__
  383. # Put it all together.
  384. msg = "%s has been deprecated. %s" % (name, doc)
  385. # Wrap it.
  386. msg = "\n" + textwrap.fill(msg, initial_indent=" ", subsequent_indent=" ")
  387. warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
  388. # Do the actual work of __new__.
  389. return object.__new__(cls)
  390. ##########################################################################
  391. # COUNTER, FOR UNIQUE NAMING
  392. ##########################################################################
  393. class Counter:
  394. """
  395. A counter that auto-increments each time its value is read.
  396. """
  397. def __init__(self, initial_value=0):
  398. self._value = initial_value
  399. def get(self):
  400. self._value += 1
  401. return self._value
  402. ##########################################################################
  403. # Search for files/binaries
  404. ##########################################################################
  405. def find_file_iter(
  406. filename,
  407. env_vars=(),
  408. searchpath=(),
  409. file_names=None,
  410. url=None,
  411. verbose=False,
  412. finding_dir=False,
  413. ):
  414. """
  415. Search for a file to be used by nltk.
  416. :param filename: The name or path of the file.
  417. :param env_vars: A list of environment variable names to check.
  418. :param file_names: A list of alternative file names to check.
  419. :param searchpath: List of directories to search.
  420. :param url: URL presented to user for download help.
  421. :param verbose: Whether or not to print path when a file is found.
  422. """
  423. file_names = [filename] + (file_names or [])
  424. assert isinstance(filename, str)
  425. assert not isinstance(file_names, str)
  426. assert not isinstance(searchpath, str)
  427. if isinstance(env_vars, str):
  428. env_vars = env_vars.split()
  429. yielded = False
  430. # File exists, no magic
  431. for alternative in file_names:
  432. path_to_file = os.path.join(filename, alternative)
  433. if os.path.isfile(path_to_file):
  434. if verbose:
  435. print("[Found %s: %s]" % (filename, path_to_file))
  436. yielded = True
  437. yield path_to_file
  438. # Check the bare alternatives
  439. if os.path.isfile(alternative):
  440. if verbose:
  441. print("[Found %s: %s]" % (filename, alternative))
  442. yielded = True
  443. yield alternative
  444. # Check if the alternative is inside a 'file' directory
  445. path_to_file = os.path.join(filename, "file", alternative)
  446. if os.path.isfile(path_to_file):
  447. if verbose:
  448. print("[Found %s: %s]" % (filename, path_to_file))
  449. yielded = True
  450. yield path_to_file
  451. # Check environment variables
  452. for env_var in env_vars:
  453. if env_var in os.environ:
  454. if finding_dir: # This is to file a directory instead of file
  455. yielded = True
  456. yield os.environ[env_var]
  457. for env_dir in os.environ[env_var].split(os.pathsep):
  458. # Check if the environment variable contains a direct path to the bin
  459. if os.path.isfile(env_dir):
  460. if verbose:
  461. print("[Found %s: %s]" % (filename, env_dir))
  462. yielded = True
  463. yield env_dir
  464. # Check if the possible bin names exist inside the environment variable directories
  465. for alternative in file_names:
  466. path_to_file = os.path.join(env_dir, alternative)
  467. if os.path.isfile(path_to_file):
  468. if verbose:
  469. print("[Found %s: %s]" % (filename, path_to_file))
  470. yielded = True
  471. yield path_to_file
  472. # Check if the alternative is inside a 'file' directory
  473. # path_to_file = os.path.join(env_dir, 'file', alternative)
  474. # Check if the alternative is inside a 'bin' directory
  475. path_to_file = os.path.join(env_dir, "bin", alternative)
  476. if os.path.isfile(path_to_file):
  477. if verbose:
  478. print("[Found %s: %s]" % (filename, path_to_file))
  479. yielded = True
  480. yield path_to_file
  481. # Check the path list.
  482. for directory in searchpath:
  483. for alternative in file_names:
  484. path_to_file = os.path.join(directory, alternative)
  485. if os.path.isfile(path_to_file):
  486. yielded = True
  487. yield path_to_file
  488. # If we're on a POSIX system, then try using the 'which' command
  489. # to find the file.
  490. if os.name == "posix":
  491. for alternative in file_names:
  492. try:
  493. p = subprocess.Popen(
  494. ["which", alternative],
  495. stdout=subprocess.PIPE,
  496. stderr=subprocess.PIPE,
  497. )
  498. stdout, stderr = p.communicate()
  499. path = _decode_stdoutdata(stdout).strip()
  500. if path.endswith(alternative) and os.path.exists(path):
  501. if verbose:
  502. print("[Found %s: %s]" % (filename, path))
  503. yielded = True
  504. yield path
  505. except (KeyboardInterrupt, SystemExit, OSError):
  506. raise
  507. finally:
  508. pass
  509. if not yielded:
  510. msg = (
  511. "NLTK was unable to find the %s file!"
  512. "\nUse software specific "
  513. "configuration paramaters" % filename
  514. )
  515. if env_vars:
  516. msg += " or set the %s environment variable" % env_vars[0]
  517. msg += "."
  518. if searchpath:
  519. msg += "\n\n Searched in:"
  520. msg += "".join("\n - %s" % d for d in searchpath)
  521. if url:
  522. msg += "\n\n For more information on %s, see:\n <%s>" % (filename, url)
  523. div = "=" * 75
  524. raise LookupError("\n\n%s\n%s\n%s" % (div, msg, div))
  525. def find_file(
  526. filename, env_vars=(), searchpath=(), file_names=None, url=None, verbose=False
  527. ):
  528. return next(
  529. find_file_iter(filename, env_vars, searchpath, file_names, url, verbose)
  530. )
  531. def find_dir(
  532. filename, env_vars=(), searchpath=(), file_names=None, url=None, verbose=False
  533. ):
  534. return next(
  535. find_file_iter(
  536. filename, env_vars, searchpath, file_names, url, verbose, finding_dir=True
  537. )
  538. )
  539. def find_binary_iter(
  540. name,
  541. path_to_bin=None,
  542. env_vars=(),
  543. searchpath=(),
  544. binary_names=None,
  545. url=None,
  546. verbose=False,
  547. ):
  548. """
  549. Search for a file to be used by nltk.
  550. :param name: The name or path of the file.
  551. :param path_to_bin: The user-supplied binary location (deprecated)
  552. :param env_vars: A list of environment variable names to check.
  553. :param file_names: A list of alternative file names to check.
  554. :param searchpath: List of directories to search.
  555. :param url: URL presented to user for download help.
  556. :param verbose: Whether or not to print path when a file is found.
  557. """
  558. for file in find_file_iter(
  559. path_to_bin or name, env_vars, searchpath, binary_names, url, verbose
  560. ):
  561. yield file
  562. def find_binary(
  563. name,
  564. path_to_bin=None,
  565. env_vars=(),
  566. searchpath=(),
  567. binary_names=None,
  568. url=None,
  569. verbose=False,
  570. ):
  571. return next(
  572. find_binary_iter(
  573. name, path_to_bin, env_vars, searchpath, binary_names, url, verbose
  574. )
  575. )
  576. def find_jar_iter(
  577. name_pattern,
  578. path_to_jar=None,
  579. env_vars=(),
  580. searchpath=(),
  581. url=None,
  582. verbose=False,
  583. is_regex=False,
  584. ):
  585. """
  586. Search for a jar that is used by nltk.
  587. :param name_pattern: The name of the jar file
  588. :param path_to_jar: The user-supplied jar location, or None.
  589. :param env_vars: A list of environment variable names to check
  590. in addition to the CLASSPATH variable which is
  591. checked by default.
  592. :param searchpath: List of directories to search.
  593. :param is_regex: Whether name is a regular expression.
  594. """
  595. assert isinstance(name_pattern, str)
  596. assert not isinstance(searchpath, str)
  597. if isinstance(env_vars, str):
  598. env_vars = env_vars.split()
  599. yielded = False
  600. # Make sure we check the CLASSPATH first
  601. env_vars = ["CLASSPATH"] + list(env_vars)
  602. # If an explicit location was given, then check it, and yield it if
  603. # it's present; otherwise, complain.
  604. if path_to_jar is not None:
  605. if os.path.isfile(path_to_jar):
  606. yielded = True
  607. yield path_to_jar
  608. else:
  609. raise LookupError(
  610. "Could not find %s jar file at %s" % (name_pattern, path_to_jar)
  611. )
  612. # Check environment variables
  613. for env_var in env_vars:
  614. if env_var in os.environ:
  615. if env_var == "CLASSPATH":
  616. classpath = os.environ["CLASSPATH"]
  617. for cp in classpath.split(os.path.pathsep):
  618. if os.path.isfile(cp):
  619. filename = os.path.basename(cp)
  620. if (
  621. is_regex
  622. and re.match(name_pattern, filename)
  623. or (not is_regex and filename == name_pattern)
  624. ):
  625. if verbose:
  626. print("[Found %s: %s]" % (name_pattern, cp))
  627. yielded = True
  628. yield cp
  629. # The case where user put directory containing the jar file in the classpath
  630. if os.path.isdir(cp):
  631. if not is_regex:
  632. if os.path.isfile(os.path.join(cp, name_pattern)):
  633. if verbose:
  634. print("[Found %s: %s]" % (name_pattern, cp))
  635. yielded = True
  636. yield os.path.join(cp, name_pattern)
  637. else:
  638. # Look for file using regular expression
  639. for file_name in os.listdir(cp):
  640. if re.match(name_pattern, file_name):
  641. if verbose:
  642. print(
  643. "[Found %s: %s]"
  644. % (
  645. name_pattern,
  646. os.path.join(cp, file_name),
  647. )
  648. )
  649. yielded = True
  650. yield os.path.join(cp, file_name)
  651. else:
  652. jar_env = os.environ[env_var]
  653. jar_iter = (
  654. (
  655. os.path.join(jar_env, path_to_jar)
  656. for path_to_jar in os.listdir(jar_env)
  657. )
  658. if os.path.isdir(jar_env)
  659. else (jar_env,)
  660. )
  661. for path_to_jar in jar_iter:
  662. if os.path.isfile(path_to_jar):
  663. filename = os.path.basename(path_to_jar)
  664. if (
  665. is_regex
  666. and re.match(name_pattern, filename)
  667. or (not is_regex and filename == name_pattern)
  668. ):
  669. if verbose:
  670. print("[Found %s: %s]" % (name_pattern, path_to_jar))
  671. yielded = True
  672. yield path_to_jar
  673. # Check the path list.
  674. for directory in searchpath:
  675. if is_regex:
  676. for filename in os.listdir(directory):
  677. path_to_jar = os.path.join(directory, filename)
  678. if os.path.isfile(path_to_jar):
  679. if re.match(name_pattern, filename):
  680. if verbose:
  681. print("[Found %s: %s]" % (filename, path_to_jar))
  682. yielded = True
  683. yield path_to_jar
  684. else:
  685. path_to_jar = os.path.join(directory, name_pattern)
  686. if os.path.isfile(path_to_jar):
  687. if verbose:
  688. print("[Found %s: %s]" % (name_pattern, path_to_jar))
  689. yielded = True
  690. yield path_to_jar
  691. if not yielded:
  692. # If nothing was found, raise an error
  693. msg = "NLTK was unable to find %s!" % name_pattern
  694. if env_vars:
  695. msg += " Set the %s environment variable" % env_vars[0]
  696. msg = textwrap.fill(msg + ".", initial_indent=" ", subsequent_indent=" ")
  697. if searchpath:
  698. msg += "\n\n Searched in:"
  699. msg += "".join("\n - %s" % d for d in searchpath)
  700. if url:
  701. msg += "\n\n For more information, on %s, see:\n <%s>" % (
  702. name_pattern,
  703. url,
  704. )
  705. div = "=" * 75
  706. raise LookupError("\n\n%s\n%s\n%s" % (div, msg, div))
  707. def find_jar(
  708. name_pattern,
  709. path_to_jar=None,
  710. env_vars=(),
  711. searchpath=(),
  712. url=None,
  713. verbose=False,
  714. is_regex=False,
  715. ):
  716. return next(
  717. find_jar_iter(
  718. name_pattern, path_to_jar, env_vars, searchpath, url, verbose, is_regex
  719. )
  720. )
  721. def find_jars_within_path(path_to_jars):
  722. return [
  723. os.path.join(root, filename)
  724. for root, dirnames, filenames in os.walk(path_to_jars)
  725. for filename in fnmatch.filter(filenames, "*.jar")
  726. ]
  727. def _decode_stdoutdata(stdoutdata):
  728. """ Convert data read from stdout/stderr to unicode """
  729. if not isinstance(stdoutdata, bytes):
  730. return stdoutdata
  731. encoding = getattr(sys.__stdout__, "encoding", locale.getpreferredencoding())
  732. if encoding is None:
  733. return stdoutdata.decode()
  734. return stdoutdata.decode(encoding)
  735. ##########################################################################
  736. # Import Stdlib Module
  737. ##########################################################################
  738. def import_from_stdlib(module):
  739. """
  740. When python is run from within the nltk/ directory tree, the
  741. current directory is included at the beginning of the search path.
  742. Unfortunately, that means that modules within nltk can sometimes
  743. shadow standard library modules. As an example, the stdlib
  744. 'inspect' module will attempt to import the stdlib 'tokenize'
  745. module, but will instead end up importing NLTK's 'tokenize' module
  746. instead (causing the import to fail).
  747. """
  748. old_path = sys.path
  749. sys.path = [d for d in sys.path if d not in ("", ".")]
  750. m = __import__(module)
  751. sys.path = old_path
  752. return m
  753. ##########################################################################
  754. # Wrapper for ElementTree Elements
  755. ##########################################################################
  756. class ElementWrapper(object):
  757. """
  758. A wrapper around ElementTree Element objects whose main purpose is
  759. to provide nicer __repr__ and __str__ methods. In addition, any
  760. of the wrapped Element's methods that return other Element objects
  761. are overridden to wrap those values before returning them.
  762. This makes Elements more convenient to work with in
  763. interactive sessions and doctests, at the expense of some
  764. efficiency.
  765. """
  766. # Prevent double-wrapping:
  767. def __new__(cls, etree):
  768. """
  769. Create and return a wrapper around a given Element object.
  770. If ``etree`` is an ``ElementWrapper``, then ``etree`` is
  771. returned as-is.
  772. """
  773. if isinstance(etree, ElementWrapper):
  774. return etree
  775. else:
  776. return object.__new__(ElementWrapper)
  777. def __init__(self, etree):
  778. r"""
  779. Initialize a new Element wrapper for ``etree``.
  780. If ``etree`` is a string, then it will be converted to an
  781. Element object using ``ElementTree.fromstring()`` first:
  782. >>> ElementWrapper("<test></test>")
  783. <Element "<?xml version='1.0' encoding='utf8'?>\n<test />">
  784. """
  785. if isinstance(etree, str):
  786. etree = ElementTree.fromstring(etree)
  787. self.__dict__["_etree"] = etree
  788. def unwrap(self):
  789. """
  790. Return the Element object wrapped by this wrapper.
  791. """
  792. return self._etree
  793. ##////////////////////////////////////////////////////////////
  794. # { String Representation
  795. ##////////////////////////////////////////////////////////////
  796. def __repr__(self):
  797. s = ElementTree.tostring(self._etree, encoding="utf8").decode("utf8")
  798. if len(s) > 60:
  799. e = s.rfind("<")
  800. if (len(s) - e) > 30:
  801. e = -20
  802. s = "%s...%s" % (s[:30], s[e:])
  803. return "<Element %r>" % s
  804. def __str__(self):
  805. """
  806. :return: the result of applying ``ElementTree.tostring()`` to
  807. the wrapped Element object.
  808. """
  809. return (
  810. ElementTree.tostring(self._etree, encoding="utf8").decode("utf8").rstrip()
  811. )
  812. ##////////////////////////////////////////////////////////////
  813. # { Element interface Delegation (pass-through)
  814. ##////////////////////////////////////////////////////////////
  815. def __getattr__(self, attrib):
  816. return getattr(self._etree, attrib)
  817. def __setattr__(self, attr, value):
  818. return setattr(self._etree, attr, value)
  819. def __delattr__(self, attr):
  820. return delattr(self._etree, attr)
  821. def __setitem__(self, index, element):
  822. self._etree[index] = element
  823. def __delitem__(self, index):
  824. del self._etree[index]
  825. def __setslice__(self, start, stop, elements):
  826. self._etree[start:stop] = elements
  827. def __delslice__(self, start, stop):
  828. del self._etree[start:stop]
  829. def __len__(self):
  830. return len(self._etree)
  831. ##////////////////////////////////////////////////////////////
  832. # { Element interface Delegation (wrap result)
  833. ##////////////////////////////////////////////////////////////
  834. def __getitem__(self, index):
  835. return ElementWrapper(self._etree[index])
  836. def __getslice__(self, start, stop):
  837. return [ElementWrapper(elt) for elt in self._etree[start:stop]]
  838. def getchildren(self):
  839. return [ElementWrapper(elt) for elt in self._etree]
  840. def getiterator(self, tag=None):
  841. return (ElementWrapper(elt) for elt in self._etree.getiterator(tag))
  842. def makeelement(self, tag, attrib):
  843. return ElementWrapper(self._etree.makeelement(tag, attrib))
  844. def find(self, path):
  845. elt = self._etree.find(path)
  846. if elt is None:
  847. return elt
  848. else:
  849. return ElementWrapper(elt)
  850. def findall(self, path):
  851. return [ElementWrapper(elt) for elt in self._etree.findall(path)]
  852. ######################################################################
  853. # Helper for Handling Slicing
  854. ######################################################################
  855. def slice_bounds(sequence, slice_obj, allow_step=False):
  856. """
  857. Given a slice, return the corresponding (start, stop) bounds,
  858. taking into account None indices and negative indices. The
  859. following guarantees are made for the returned start and stop values:
  860. - 0 <= start <= len(sequence)
  861. - 0 <= stop <= len(sequence)
  862. - start <= stop
  863. :raise ValueError: If ``slice_obj.step`` is not None.
  864. :param allow_step: If true, then the slice object may have a
  865. non-None step. If it does, then return a tuple
  866. (start, stop, step).
  867. """
  868. start, stop = (slice_obj.start, slice_obj.stop)
  869. # If allow_step is true, then include the step in our return
  870. # value tuple.
  871. if allow_step:
  872. step = slice_obj.step
  873. if step is None:
  874. step = 1
  875. # Use a recursive call without allow_step to find the slice
  876. # bounds. If step is negative, then the roles of start and
  877. # stop (in terms of default values, etc), are swapped.
  878. if step < 0:
  879. start, stop = slice_bounds(sequence, slice(stop, start))
  880. else:
  881. start, stop = slice_bounds(sequence, slice(start, stop))
  882. return start, stop, step
  883. # Otherwise, make sure that no non-default step value is used.
  884. elif slice_obj.step not in (None, 1):
  885. raise ValueError(
  886. "slices with steps are not supported by %s" % sequence.__class__.__name__
  887. )
  888. # Supply default offsets.
  889. if start is None:
  890. start = 0
  891. if stop is None:
  892. stop = len(sequence)
  893. # Handle negative indices.
  894. if start < 0:
  895. start = max(0, len(sequence) + start)
  896. if stop < 0:
  897. stop = max(0, len(sequence) + stop)
  898. # Make sure stop doesn't go past the end of the list. Note that
  899. # we avoid calculating len(sequence) if possible, because for lazy
  900. # sequences, calculating the length of a sequence can be expensive.
  901. if stop > 0:
  902. try:
  903. sequence[stop - 1]
  904. except IndexError:
  905. stop = len(sequence)
  906. # Make sure start isn't past stop.
  907. start = min(start, stop)
  908. # That's all folks!
  909. return start, stop
  910. ######################################################################
  911. # Permission Checking
  912. ######################################################################
  913. def is_writable(path):
  914. # Ensure that it exists.
  915. if not os.path.exists(path):
  916. return False
  917. # If we're on a posix system, check its permissions.
  918. if hasattr(os, "getuid"):
  919. statdata = os.stat(path)
  920. perm = stat.S_IMODE(statdata.st_mode)
  921. # is it world-writable?
  922. if perm & 0o002:
  923. return True
  924. # do we own it?
  925. elif statdata.st_uid == os.getuid() and (perm & 0o200):
  926. return True
  927. # are we in a group that can write to it?
  928. elif (statdata.st_gid in [os.getgid()] + os.getgroups()) and (perm & 0o020):
  929. return True
  930. # otherwise, we can't write to it.
  931. else:
  932. return False
  933. # Otherwise, we'll assume it's writable.
  934. # [xx] should we do other checks on other platforms?
  935. return True
  936. ######################################################################
  937. # NLTK Error reporting
  938. ######################################################################
  939. def raise_unorderable_types(ordering, a, b):
  940. raise TypeError(
  941. "unorderable types: %s() %s %s()"
  942. % (type(a).__name__, ordering, type(b).__name__)
  943. )