METADATA 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. Metadata-Version: 2.0
  2. Name: parse
  3. Version: 1.12.0
  4. Summary: parse() is the opposite of format()
  5. Home-page: https://github.com/r1chardj0n3s/parse
  6. Author: Richard Jones
  7. Author-email: richard@python.org
  8. License: UNKNOWN
  9. Platform: UNKNOWN
  10. Classifier: Environment :: Web Environment
  11. Classifier: Intended Audience :: Developers
  12. Classifier: Programming Language :: Python :: 2.7
  13. Classifier: Programming Language :: Python :: 3.4
  14. Classifier: Programming Language :: Python :: 3.5
  15. Classifier: Programming Language :: Python :: 3.6
  16. Classifier: Topic :: Software Development :: Code Generators
  17. Classifier: Topic :: Software Development :: Libraries :: Python Modules
  18. Classifier: License :: OSI Approved :: BSD License
  19. Parse strings using a specification based on the Python format() syntax.
  20. ``parse()`` is the opposite of ``format()``
  21. The module is set up to only export ``parse()``, ``search()``, ``findall()``,
  22. and ``with_pattern()`` when ``import \*`` is used:
  23. >>> from parse import *
  24. >From there it's a simple thing to parse a string:
  25. >>> parse("It's {}, I love it!", "It's spam, I love it!")
  26. <Result ('spam',) {}>
  27. >>> _[0]
  28. 'spam'
  29. Or to search a string for some pattern:
  30. >>> search('Age: {:d}\n', 'Name: Rufus\nAge: 42\nColor: red\n')
  31. <Result (42,) {}>
  32. Or find all the occurrences of some pattern in a string:
  33. >>> ''.join(r.fixed[0] for r in findall(">{}<", "<p>the <b>bold</b> text</p>"))
  34. 'the bold text'
  35. If you're going to use the same pattern to match lots of strings you can
  36. compile it once:
  37. >>> from parse import compile
  38. >>> p = compile("It's {}, I love it!")
  39. >>> print(p)
  40. <Parser "It's {}, I love it!">
  41. >>> p.parse("It's spam, I love it!")
  42. <Result ('spam',) {}>
  43. ("compile" is not exported for ``import *`` usage as it would override the
  44. built-in ``compile()`` function)
  45. The default behaviour is to match strings case insensitively. You may match with
  46. case by specifying `case_sensitive=True`:
  47. >>> parse('SPAM', 'spam', case_sensitive=True) is None
  48. True
  49. Format Syntax
  50. -------------
  51. A basic version of the `Format String Syntax`_ is supported with anonymous
  52. (fixed-position), named and formatted fields::
  53. {[field name]:[format spec]}
  54. Field names must be a valid Python identifiers, including dotted names;
  55. element indexes imply dictionaries (see below for example).
  56. Numbered fields are also not supported: the result of parsing will include
  57. the parsed fields in the order they are parsed.
  58. The conversion of fields to types other than strings is done based on the
  59. type in the format specification, which mirrors the ``format()`` behaviour.
  60. There are no "!" field conversions like ``format()`` has.
  61. Some simple parse() format string examples:
  62. >>> parse("Bring me a {}", "Bring me a shrubbery")
  63. <Result ('shrubbery',) {}>
  64. >>> r = parse("The {} who say {}", "The knights who say Ni!")
  65. >>> print(r)
  66. <Result ('knights', 'Ni!') {}>
  67. >>> print(r.fixed)
  68. ('knights', 'Ni!')
  69. >>> r = parse("Bring out the holy {item}", "Bring out the holy hand grenade")
  70. >>> print(r)
  71. <Result () {'item': 'hand grenade'}>
  72. >>> print(r.named)
  73. {'item': 'hand grenade'}
  74. >>> print(r['item'])
  75. hand grenade
  76. >>> 'item' in r
  77. True
  78. Note that `in` only works if you have named fields. Dotted names and indexes
  79. are possible though the application must make additional sense of the result:
  80. >>> r = parse("Mmm, {food.type}, I love it!", "Mmm, spam, I love it!")
  81. >>> print(r)
  82. <Result () {'food.type': 'spam'}>
  83. >>> print(r.named)
  84. {'food.type': 'spam'}
  85. >>> print(r['food.type'])
  86. spam
  87. >>> r = parse("My quest is {quest[name]}", "My quest is to seek the holy grail!")
  88. >>> print(r)
  89. <Result () {'quest': {'name': 'to seek the holy grail!'}}>
  90. >>> print(r['quest'])
  91. {'name': 'to seek the holy grail!'}
  92. >>> print(r['quest']['name'])
  93. to seek the holy grail!
  94. If the text you're matching has braces in it you can match those by including
  95. a double-brace ``{{`` or ``}}`` in your format string, just like format() does.
  96. Format Specification
  97. --------------------
  98. Most often a straight format-less ``{}`` will suffice where a more complex
  99. format specification might have been used.
  100. Most of `format()`'s `Format Specification Mini-Language`_ is supported:
  101. [[fill]align][0][width][.precision][type]
  102. The differences between `parse()` and `format()` are:
  103. - The align operators will cause spaces (or specified fill character) to be
  104. stripped from the parsed value. The width is not enforced; it just indicates
  105. there may be whitespace or "0"s to strip.
  106. - Numeric parsing will automatically handle a "0b", "0o" or "0x" prefix.
  107. That is, the "#" format character is handled automatically by d, b, o
  108. and x formats. For "d" any will be accepted, but for the others the correct
  109. prefix must be present if at all.
  110. - Numeric sign is handled automatically.
  111. - The thousands separator is handled automatically if the "n" type is used.
  112. - The types supported are a slightly different mix to the format() types. Some
  113. format() types come directly over: "d", "n", "%", "f", "e", "b", "o" and "x".
  114. In addition some regular expression character group types "D", "w", "W", "s"
  115. and "S" are also available.
  116. - The "e" and "g" types are case-insensitive so there is not need for
  117. the "E" or "G" types.
  118. ===== =========================================== ========
  119. Type Characters Matched Output
  120. ===== =========================================== ========
  121. l Letters (ASCII) str
  122. w Letters, numbers and underscore str
  123. W Not letters, numbers and underscore str
  124. s Whitespace str
  125. S Non-whitespace str
  126. d Digits (effectively integer numbers) int
  127. D Non-digit str
  128. n Numbers with thousands separators (, or .) int
  129. % Percentage (converted to value/100.0) float
  130. f Fixed-point numbers float
  131. F Decimal numbers Decimal
  132. e Floating-point numbers with exponent float
  133. e.g. 1.1e-10, NAN (all case insensitive)
  134. g General number format (either d, f or e) float
  135. b Binary numbers int
  136. o Octal numbers int
  137. x Hexadecimal numbers (lower and upper case) int
  138. ti ISO 8601 format date/time datetime
  139. e.g. 1972-01-20T10:21:36Z ("T" and "Z"
  140. optional)
  141. te RFC2822 e-mail format date/time datetime
  142. e.g. Mon, 20 Jan 1972 10:21:36 +1000
  143. tg Global (day/month) format date/time datetime
  144. e.g. 20/1/1972 10:21:36 AM +1:00
  145. ta US (month/day) format date/time datetime
  146. e.g. 1/20/1972 10:21:36 PM +10:30
  147. tc ctime() format date/time datetime
  148. e.g. Sun Sep 16 01:03:52 1973
  149. th HTTP log format date/time datetime
  150. e.g. 21/Nov/2011:00:07:11 +0000
  151. ts Linux system log format date/time datetime
  152. e.g. Nov 9 03:37:44
  153. tt Time time
  154. e.g. 10:21:36 PM -5:30
  155. ===== =========================================== ========
  156. Some examples of typed parsing with ``None`` returned if the typing
  157. does not match:
  158. >>> parse('Our {:d} {:w} are...', 'Our 3 weapons are...')
  159. <Result (3, 'weapons') {}>
  160. >>> parse('Our {:d} {:w} are...', 'Our three weapons are...')
  161. >>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')
  162. <Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>
  163. And messing about with alignment:
  164. >>> parse('with {:>} herring', 'with a herring')
  165. <Result ('a',) {}>
  166. >>> parse('spam {:^} spam', 'spam lovely spam')
  167. <Result ('lovely',) {}>
  168. Note that the "center" alignment does not test to make sure the value is
  169. centered - it just strips leading and trailing whitespace.
  170. Width and precision may be used to restrict the size of matched text
  171. from the input. Width specifies a minimum size and precision specifies
  172. a maximum. For example:
  173. >>> parse('{:.2}{:.2}', 'look') # specifying precision
  174. <Result ('lo', 'ok') {}>
  175. >>> parse('{:4}{:4}', 'look at that') # specifying width
  176. <Result ('look', 'at that') {}>
  177. >>> parse('{:4}{:.4}', 'look at that') # specifying both
  178. <Result ('look at ', 'that') {}>
  179. >>> parse('{:2d}{:2d}', '0440') # parsing two contiguous numbers
  180. <Result (4, 40) {}>
  181. Some notes for the date and time types:
  182. - the presence of the time part is optional (including ISO 8601, starting
  183. at the "T"). A full datetime object will always be returned; the time
  184. will be set to 00:00:00. You may also specify a time without seconds.
  185. - when a seconds amount is present in the input fractions will be parsed
  186. to give microseconds.
  187. - except in ISO 8601 the day and month digits may be 0-padded.
  188. - the date separator for the tg and ta formats may be "-" or "/".
  189. - named months (abbreviations or full names) may be used in the ta and tg
  190. formats in place of numeric months.
  191. - as per RFC 2822 the e-mail format may omit the day (and comma), and the
  192. seconds but nothing else.
  193. - hours greater than 12 will be happily accepted.
  194. - the AM/PM are optional, and if PM is found then 12 hours will be added
  195. to the datetime object's hours amount - even if the hour is greater
  196. than 12 (for consistency.)
  197. - in ISO 8601 the "Z" (UTC) timezone part may be a numeric offset
  198. - timezones are specified as "+HH:MM" or "-HH:MM". The hour may be one or two
  199. digits (0-padded is OK.) Also, the ":" is optional.
  200. - the timezone is optional in all except the e-mail format (it defaults to
  201. UTC.)
  202. - named timezones are not handled yet.
  203. Note: attempting to match too many datetime fields in a single parse() will
  204. currently result in a resource allocation issue. A TooManyFields exception
  205. will be raised in this instance. The current limit is about 15. It is hoped
  206. that this limit will be removed one day.
  207. .. _`Format String Syntax`:
  208. http://docs.python.org/library/string.html#format-string-syntax
  209. .. _`Format Specification Mini-Language`:
  210. http://docs.python.org/library/string.html#format-specification-mini-language
  211. Result and Match Objects
  212. ------------------------
  213. The result of a ``parse()`` and ``search()`` operation is either ``None`` (no match), a
  214. ``Result`` instance or a ``Match`` instance if ``evaluate_result`` is False.
  215. The ``Result`` instance has three attributes:
  216. fixed
  217. A tuple of the fixed-position, anonymous fields extracted from the input.
  218. named
  219. A dictionary of the named fields extracted from the input.
  220. spans
  221. A dictionary mapping the names and fixed position indices matched to a
  222. 2-tuple slice range of where the match occurred in the input.
  223. The span does not include any stripped padding (alignment or width).
  224. The ``Match`` instance has one method:
  225. evaluate_result()
  226. Generates and returns a ``Result`` instance for this ``Match`` object.
  227. Custom Type Conversions
  228. -----------------------
  229. If you wish to have matched fields automatically converted to your own type you
  230. may pass in a dictionary of type conversion information to ``parse()`` and
  231. ``compile()``.
  232. The converter will be passed the field string matched. Whatever it returns
  233. will be substituted in the ``Result`` instance for that field.
  234. Your custom type conversions may override the builtin types if you supply one
  235. with the same identifier.
  236. >>> def shouty(string):
  237. ... return string.upper()
  238. ...
  239. >>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))
  240. <Result ('HELLO',) {}>
  241. If the type converter has the optional ``pattern`` attribute, it is used as
  242. regular expression for better pattern matching (instead of the default one).
  243. >>> def parse_number(text):
  244. ... return int(text)
  245. >>> parse_number.pattern = r'\d+'
  246. >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
  247. <Result () {'number': 42}>
  248. >>> _ = parse('Answer: {:Number}', 'Answer: Alice', dict(Number=parse_number))
  249. >>> assert _ is None, "MISMATCH"
  250. You can also use the ``with_pattern(pattern)`` decorator to add this
  251. information to a type converter function:
  252. >>> from parse import with_pattern
  253. >>> @with_pattern(r'\d+')
  254. ... def parse_number(text):
  255. ... return int(text)
  256. >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
  257. <Result () {'number': 42}>
  258. A more complete example of a custom type might be:
  259. >>> yesno_mapping = {
  260. ... "yes": True, "no": False,
  261. ... "on": True, "off": False,
  262. ... "true": True, "false": False,
  263. ... }
  264. >>> @with_pattern(r"|".join(yesno_mapping))
  265. ... def parse_yesno(text):
  266. ... return yesno_mapping[text.lower()]
  267. If the type converter ``pattern`` uses regex-grouping (with parenthesis),
  268. you should indicate this by using the optional ``regex_group_count`` parameter
  269. in the ``with_pattern()`` decorator:
  270. >>> @with_pattern(r'((\d+))', regex_group_count=2)
  271. ... def parse_number2(text):
  272. ... return int(text)
  273. >>> parse('Answer: {:Number2} {:Number2}', 'Answer: 42 43', dict(Number2=parse_number2))
  274. <Result (42, 43) {}>
  275. Otherwise, this may cause parsing problems with unnamed/fixed parameters.
  276. Potential Gotchas
  277. -----------------
  278. `parse()` will always match the shortest text necessary (from left to right)
  279. to fulfil the parse pattern, so for example:
  280. >>> pattern = '{dir1}/{dir2}'
  281. >>> data = 'root/parent/subdir'
  282. >>> sorted(parse(pattern, data).named.items())
  283. [('dir1', 'root'), ('dir2', 'parent/subdir')]
  284. So, even though `{'dir1': 'root/parent', 'dir2': 'subdir'}` would also fit
  285. the pattern, the actual match represents the shortest successful match for
  286. `dir1`.
  287. ----
  288. **Version history (in brief)**:
  289. - 1.12.0 Do not assume closing brace when an opening one is found (thanks @mattsep)
  290. - 1.11.1 Revert having unicode char in docstring, it breaks Bamboo builds(?!)
  291. - 1.11.0 Implement `__contains__` for Result instances.
  292. - 1.10.0 Introduce a "letters" matcher, since "w" matches numbers
  293. also.
  294. - 1.9.1 Fix deprecation warnings around backslashes in regex strings
  295. (thanks Mickael Schoentgen). Also fix some documentation formatting
  296. issues.
  297. - 1.9.0 We now honor precision and width specifiers when parsing numbers
  298. and strings, allowing parsing of concatenated elements of fixed width
  299. (thanks Julia Signell)
  300. - 1.8.4 Add LICENSE file at request of packagers.
  301. Correct handling of AM/PM to follow most common interpretation.
  302. Correct parsing of hexadecimal that looks like a binary prefix.
  303. Add ability to parse case sensitively.
  304. Add parsing of numbers to Decimal with "F" (thanks John Vandenberg)
  305. - 1.8.3 Add regex_group_count to with_pattern() decorator to support
  306. user-defined types that contain brackets/parenthesis (thanks Jens Engel)
  307. - 1.8.2 add documentation for including braces in format string
  308. - 1.8.1 ensure bare hexadecimal digits are not matched
  309. - 1.8.0 support manual control over result evaluation (thanks Timo Furrer)
  310. - 1.7.0 parse dict fields (thanks Mark Visser) and adapted to allow
  311. more than 100 re groups in Python 3.5+ (thanks David King)
  312. - 1.6.6 parse Linux system log dates (thanks Alex Cowan)
  313. - 1.6.5 handle precision in float format (thanks Levi Kilcher)
  314. - 1.6.4 handle pipe "|" characters in parse string (thanks Martijn Pieters)
  315. - 1.6.3 handle repeated instances of named fields, fix bug in PM time
  316. overflow
  317. - 1.6.2 fix logging to use local, not root logger (thanks Necku)
  318. - 1.6.1 be more flexible regarding matched ISO datetimes and timezones in
  319. general, fix bug in timezones without ":" and improve docs
  320. - 1.6.0 add support for optional ``pattern`` attribute in user-defined types
  321. (thanks Jens Engel)
  322. - 1.5.3 fix handling of question marks
  323. - 1.5.2 fix type conversion error with dotted names (thanks Sebastian Thiel)
  324. - 1.5.1 implement handling of named datetime fields
  325. - 1.5 add handling of dotted field names (thanks Sebastian Thiel)
  326. - 1.4.1 fix parsing of "0" in int conversion (thanks James Rowe)
  327. - 1.4 add __getitem__ convenience access on Result.
  328. - 1.3.3 fix Python 2.5 setup.py issue.
  329. - 1.3.2 fix Python 3.2 setup.py issue.
  330. - 1.3.1 fix a couple of Python 3.2 compatibility issues.
  331. - 1.3 added search() and findall(); removed compile() from ``import *``
  332. export as it overwrites builtin.
  333. - 1.2 added ability for custom and override type conversions to be
  334. provided; some cleanup
  335. - 1.1.9 to keep things simpler number sign is handled automatically;
  336. significant robustification in the face of edge-case input.
  337. - 1.1.8 allow "d" fields to have number base "0x" etc. prefixes;
  338. fix up some field type interactions after stress-testing the parser;
  339. implement "%" type.
  340. - 1.1.7 Python 3 compatibility tweaks (2.5 to 2.7 and 3.2 are supported).
  341. - 1.1.6 add "e" and "g" field types; removed redundant "h" and "X";
  342. removed need for explicit "#".
  343. - 1.1.5 accept textual dates in more places; Result now holds match span
  344. positions.
  345. - 1.1.4 fixes to some int type conversion; implemented "=" alignment; added
  346. date/time parsing with a variety of formats handled.
  347. - 1.1.3 type conversion is automatic based on specified field types. Also added
  348. "f" and "n" types.
  349. - 1.1.2 refactored, added compile() and limited ``from parse import *``
  350. - 1.1.1 documentation improvements
  351. - 1.1.0 implemented more of the `Format Specification Mini-Language`_
  352. and removed the restriction on mixing fixed-position and named fields
  353. - 1.0.0 initial release
  354. This code is copyright 2012-2019 Richard Jones <richard@python.org>
  355. See the end of the source file for the license of use.