forked from adamlaska/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpunctuation_chars.py
More file actions
212 lines (169 loc) · 9.25 KB
/
punctuation_chars.py
File metadata and controls
212 lines (169 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python
# -*- coding: utf8 -*-
# :Copyright: © 2011 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.
#
# .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
# :Id: $Id: punctuation_chars.py 7401 2012-05-01 09:50:02Z grubert $
import sys, re
import unicodedata
# punctuation characters around inline markup
# ===========================================
#
# This module provides the lists of characters for the implementation of
# the `inline markup recognition rules`_ in the reStructuredText parser
# (states.py)
#
# .. _inline markup recognition rules:
# ../../../docs/ref/rst/restructuredtext.html#inline-markup
# Docutils punctuation category sample strings
# --------------------------------------------
#
# The sample strings are generated by punctuation_samples() and put here
# literal to avoid the time-consuming generation with every Docutils
# run. Running this file as a standalone module checks the definitions below
# against a re-calculation.
openers = ur"""\"\'\(\<\[\{༺༼᚛⁅⁽₍〈❨❪❬❮❰❲❴⟅⟦⟨⟪⟬⟮⦃⦅⦇⦉⦋⦍⦏⦑⦓⦕⦗⧘⧚⧼⸢⸤⸦⸨〈《「『【〔〖〘〚〝〝﴾︗︵︷︹︻︽︿﹁﹃﹇﹙﹛﹝([{⦅「«‘“‹⸂⸄⸉⸌⸜⸠‚„»’”›⸃⸅⸊⸍⸝⸡‛‟"""
closers = ur"""\"\'\)\>\]\}༻༽᚜⁆⁾₎〉❩❫❭❯❱❳❵⟆⟧⟩⟫⟭⟯⦄⦆⦈⦊⦌⦎⦐⦒⦔⦖⦘⧙⧛⧽⸣⸥⸧⸩〉》」』】〕〗〙〛〞〟﴿︘︶︸︺︼︾﹀﹂﹄﹈﹚﹜﹞)]}⦆」»’”›⸃⸅⸊⸍⸝⸡‛‟«‘“‹⸂⸄⸉⸌⸜⸠‚„"""
delimiters = ur"\-\/\:֊־᐀᠆‐‑‒–—―⸗⸚〜〰゠︱︲﹘﹣-¡·¿;·՚՛՜՝՞՟։׀׃׆׳״؉؊،؍؛؞؟٪٫٬٭۔܀܁܂܃܄܅܆܇܈܉܊܋܌܍߷߸߹࠰࠱࠲࠳࠴࠵࠶࠷࠸࠹࠺࠻࠼࠽࠾।॥॰෴๏๚๛༄༅༆༇༈༉༊་༌།༎༏༐༑༒྅࿐࿑࿒࿓࿔၊။၌၍၎၏჻፡።፣፤፥፦፧፨᙭᙮᛫᛬᛭᜵᜶។៕៖៘៙៚᠀᠁᠂᠃᠄᠅᠇᠈᠉᠊᥄᥅᧞᧟᨞᨟᪠᪡᪢᪣᪤᪥᪦᪨᪩᪪᪫᪬᪭᭚᭛᭜᭝᭞᭟᭠᰻᰼᰽᰾᰿᱾᱿᳓‖‗†‡•‣․‥…‧‰‱′″‴‵‶‷‸※‼‽‾⁁⁂⁃⁇⁈⁉⁊⁋⁌⁍⁎⁏⁐⁑⁓⁕⁖⁗⁘⁙⁚⁛⁜⁝⁞⳹⳺⳻⳼⳾⳿⸀⸁⸆⸇⸈⸋⸎⸏⸐⸑⸒⸓⸔⸕⸖⸘⸙⸛⸞⸟⸪⸫⸬⸭⸮⸰⸱、。〃〽・꓾꓿꘍꘎꘏꙳꙾꛲꛳꛴꛵꛶꛷꡴꡵꡶꡷꣎꣏꣸꣹꣺꤮꤯꥟꧁꧂꧃꧄꧅꧆꧇꧈꧉꧊꧋꧌꧍꧞꧟꩜꩝꩞꩟꫞꫟꯫︐︑︒︓︔︕︖︙︰﹅﹆﹉﹊﹋﹌﹐﹑﹒﹔﹕﹖﹗﹟﹠﹡﹨﹪﹫!"#%&'*,./:;?@\。、・𐄀𐄁𐎟𐏐𐡗𐤟𐤿𐩐𐩑𐩒𐩓𐩔𐩕𐩖𐩗𐩘𐩿𐬹𐬺𐬻𐬼𐬽𐬾𐬿𑂻𑂼𑂾𑂿𑃀𑃁𒑰𒑱𒑲𒑳"
closing_delimiters = ur"\.\,\;\!\?"
# Unicode punctuation character categories
# ----------------------------------------
unicode_punctuation_categories = {
# 'Pc': 'Connector', # not used in Docutils inline markup recognition
'Pd': 'Dash',
'Ps': 'Open',
'Pe': 'Close',
'Pi': 'Initial quote', # may behave like Ps or Pe depending on usage
'Pf': 'Final quote', # may behave like Ps or Pe depending on usage
'Po': 'Other'
}
"""Unicode character categories for punctuation"""
# generate character pattern strings
# ==================================
def unicode_charlists(categories, cp_min=0, cp_max=None):
"""Return dictionary of Unicode character lists.
For each of the `catagories`, an item contains a list with all Unicode
characters with `cp_min` <= code-point <= `cp_max` that belong to the
category. (The default values check every code-point supported by Python.)
"""
# Determine highest code point with one of the given categories
# (may shorten the search time considerably if there are many
# categories with not too high characters):
if cp_max is None:
# python 2.3: list comprehension instead of generator required
cp_max = max([x for x in xrange(sys.maxunicode + 1)
if unicodedata.category(unichr(x)) in categories])
# print cp_max # => 74867 for unicode_punctuation_categories
charlists = {}
for cat in categories:
charlists[cat] = [unichr(x) for x in xrange(cp_min, cp_max+1)
if unicodedata.category(unichr(x)) == cat]
return charlists
# Character categories in Docutils
# --------------------------------
def punctuation_samples():
"""Docutils punctuation category sample strings.
Return list of sample strings for the categories "Open", "Close",
"Delimiters" and "Closing-Delimiters" used in the `inline markup
recognition rules`_.
"""
# Lists with characters in Unicode punctuation character categories
cp_min = 160 # ASCII chars have special rules for backwards compatibility
ucharlists = unicode_charlists(unicode_punctuation_categories, cp_min)
# match opening/closing characters
# --------------------------------
# Rearange the lists to ensure matching characters at the same
# index position.
# low quotation marks are also used as closers (e.g. in Greek)
# move them to category Pi:
ucharlists['Ps'].remove(u'‚') # 201A SINGLE LOW-9 QUOTATION MARK
ucharlists['Ps'].remove(u'„') # 201E DOUBLE LOW-9 QUOTATION MARK
ucharlists['Pi'] += [u'‚', u'„']
ucharlists['Pi'].remove(u'‛') # 201B SINGLE HIGH-REVERSED-9 QUOTATION MARK
ucharlists['Pi'].remove(u'‟') # 201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
ucharlists['Pf'] += [u'‛', u'‟']
# 301F LOW DOUBLE PRIME QUOTATION MARK misses the opening pendant:
ucharlists['Ps'].insert(ucharlists['Pe'].index(u'\u301f'), u'\u301d')
# print u''.join(ucharlists['Ps']).encode('utf8')
# print u''.join(ucharlists['Pe']).encode('utf8')
# print u''.join(ucharlists['Pi']).encode('utf8')
# print u''.join(ucharlists['Pf']).encode('utf8')
# The Docutils character categories
# ---------------------------------
#
# The categorization of ASCII chars is non-standard to reduce both
# false positives and need for escaping. (see `inline markup recognition
# rules`_)
# matching, allowed before markup
openers = [re.escape('"\'(<[{')]
for cat in ('Ps', 'Pi', 'Pf'):
openers.extend(ucharlists[cat])
# matching, allowed after markup
closers = [re.escape('"\')>]}')]
for cat in ('Pe', 'Pf', 'Pi'):
closers.extend(ucharlists[cat])
# non-matching, allowed on both sides
delimiters = [re.escape('-/:')]
for cat in ('Pd', 'Po'):
delimiters.extend(ucharlists[cat])
# non-matching, after markup
closing_delimiters = [re.escape('.,;!?')]
# # Test open/close matching:
# for i in range(min(len(openers),len(closers))):
# print '%4d %s %s' % (i, openers[i].encode('utf8'),
# closers[i].encode('utf8'))
return [u''.join(chars)
for chars in (openers, closers, delimiters, closing_delimiters)]
# Matching open/close quotes
# --------------------------
# Rule (5) requires determination of matching open/close pairs. However,
# the pairing of open/close quotes is ambigue due to different typographic
# conventions in different languages.
quote_pairs = {u'\xbb': u'\xbb', # Swedish
u'\u2018': u'\u201a', # Greek
u'\u2019': u'\u2019', # Swedish
u'\u201a': u'\u2018\u2019', # German, Polish
u'\u201c': u'\u201e', # German
u'\u201e': u'\u201c\u201d',
u'\u201d': u'\u201d', # Swedish
u'\u203a': u'\u203a', # Swedish
}
def match_chars(c1, c2):
try:
i = openers.index(c1)
except ValueError: # c1 not in openers
return False
return c2 == closers[i] or c2 in quote_pairs.get(c1, '')
# print results
# =============
if __name__ == '__main__':
# (re) create and compare the samples:
(o, c, d, cd) = punctuation_samples()
if o != openers:
print '- openers = ur"""%s"""' % openers.encode('utf8')
print '+ openers = ur"""%s"""' % o.encode('utf8')
if c != closers:
print '- closers = ur"""%s"""' % closers.encode('utf8')
print '+ closers = ur"""%s"""' % c.encode('utf8')
if d != delimiters:
print '- delimiters = ur"%s"' % delimiters.encode('utf8')
print '+ delimiters = ur"%s"' % d.encode('utf8')
if cd != closing_delimiters:
print '- closing_delimiters = ur"%s"' % closing_delimiters.encode('utf8')
print '+ closing_delimiters = ur"%s"' % cd.encode('utf8')
# # test prints
# print 'openers = ', repr(openers)
# print 'closers = ', repr(closers)
# print 'delimiters = ', repr(delimiters)
# print 'closing_delimiters = ', repr(closing_delimiters)
# ucharlists = unicode_charlists(unicode_punctuation_categories)
# for cat, chars in ucharlists.items():
# # print cat, chars
# # compact output (visible with a comprehensive font):
# print (u":%s: %s" % (cat, u''.join(chars))).encode('utf8')