def id( s ): s = u( s ) s = unidecode( s ) # возвращает ascii s = u( s ) s = s.strip() s = brackets( s ) s = full( s ) s = s.lower() s = spaces( s ) s = s.replace( u' ', u'_' ) s = re.sub( non_id_re, u'_', s ) s = u( s ) return s
def id(s): s = u(s) s = unidecode(s) # возвращает ascii s = u(s) s = s.strip() s = brackets(s) s = full(s) s = s.lower() s = spaces(s) s = s.replace(u' ', u'_') s = re.sub(non_id_re, u'_', s) s = u(s) return s
def short( s ): ''' short( 'seq[uence]' ) -> 'seq' короткий вариант строки с квадратными скобками ''' return spaces( re.sub( del_brackets_re, u'', u( s )))
def full(s): ''' full( 'seq[uence]' ) -> 'sequence' длинный вариант строки с квадратными скобками ''' return u(s).replace(u'[', u'').replace(u']', u'')
def short(s): ''' short( 'seq[uence]' ) -> 'seq' короткий вариант строки с квадратными скобками ''' return spaces(re.sub(del_brackets_re, u'', u(s)))
def full( s ): ''' full( 'seq[uence]' ) -> 'sequence' длинный вариант строки с квадратными скобками ''' return u( s ).replace( u'[', u'' ).replace( u']', u'' )
def GetDiameter(arg, d): '''Given the command line arguments collapsed into a space-separated string, return the command and the diameter in inches that the user requested data for. ''' try: s, unit = ParseUnit(arg, allow_expr=True) except ValueError as e: Error(e) try: diam = float(eval(s)) except Exception: Error("Can't evaluate '{}'".format(s)) if diam <= 0: Error("Negative or zero diameter is meaningless.") unit = unit if unit else "inches" diam_inches = diam * u(unit) / u("inches") return arg, diam_inches
def testUFromCustom__unicode__(self): class C(object): def __init__(self, s): self.s = s def __unicode__(self): return self.s self.assertTypeEquals(self.richuni, u(C(self.richuni)))
def testUFromCustom__str__(self): class C(object): def __init__(self, s): self.s = s def __str__(self): return self.s # randomn rubbish self.assertTypeEquals(self.richuni, u(C(self.richstr)))
def set_headers(self, headers): ''' set_headers([ {title: str, value: str}, ...]) ''' # альтернативный вариант default value для изменяемых типов headers = headers if headers else [] # переписать себе for h in headers: self.headers[h['title']] = u(h['value'])
def set_headers( self, headers ): ''' set_headers([ {title: str, value: str}, ...]) ''' # альтернативный вариант default value для изменяемых типов headers = headers if headers else [] # переписать себе for h in headers: self.headers[ h[ 'title' ]] = u( h[ 'value' ])
def read( self, f ): ''' считывает статью из файла. предполагается, что статьи разделны хотя бы одной пустой строкой в случае неудачи (например, EOF) возвращает None может делегировать вызов плагину self.plugin.read( f ) -> tuple( title, entry ) -> None // в случае неудачи ''' if hasattr( self.plugin, 'read' ): _ = self.plugin.read( f ) if _: self.title, self.entry = _[ 0 ], _[ 1 ].strip() return self return None self.title = u'' # пропустить пустые строки while True: _ = u( f.readline()) if _ is not u'\n': self.title = _.strip() break # print u'dslEntry.read: прочитал заголовок "%s"' % self.title self.entry = u'' # читать до пустой строки или EOF while True: line = u( f.readline()) if line.strip() is not u'': self.entry += line else: break self.entry = self.entry.strip() if len( self.entry ) == 0: return None return self
def lowercase_string_by_removing_pinyin_tones(s): '''lowercase_string_by_removing_pinyin_tones(string) --> unicode simplify / plainize chinese pinyin by converting it to lower case and removing diacritics from letters 'a', 'e', 'o', 'u', i'. ''' s = u(s).lower() for diacrs, normal in _diacritics: for diacr in diacrs: s = s.replace(diacr, normal) return s
def read(self, f): ''' считывает статью из файла. предполагается, что статьи разделны хотя бы одной пустой строкой в случае неудачи (например, EOF) возвращает None может делегировать вызов плагину self.plugin.read( f ) -> tuple( title, entry ) -> None // в случае неудачи ''' if hasattr(self.plugin, 'read'): _ = self.plugin.read(f) if _: self.title, self.entry = _[0], _[1].strip() return self return None self.title = u'' # пропустить пустые строки while True: _ = u(f.readline()) if _ is not u'\n': self.title = _.strip() break self.entry = u'' # читать до пустой строки или EOF # именно пустой, а не содержащей пробелы while True: line = u(f.readline()) if line != u'\n' and line != u'': self.entry += line else: break self.entry = self.entry.strip() if len(self.entry) == 0: return None return self
def brackets(s): r''' замена всех вариантов скобок на квадратные [] заменяются такие комбинации: { \[ ... \] } { ( } ... { ) } { ( ... ) } { ... } ''' s = u(s) if s.find(u'{') is not -1: # -1 значит не найденно for exp, sub in re_sub: s = re.sub(exp, sub, s) return spaces(s)
def brackets( s ): r''' замена всех вариантов скобок на квадратные [] заменяются такие комбинации: { \[ ... \] } { ( } ... { ) } { ( ... ) } { ... } ''' s = u( s ) if s.find( u'{' ) is not -1: # -1 значит не найденно for exp, sub in re_sub: s = re.sub( exp, sub, s ) return spaces( s )
def step2( text ): # обернуть text = u'%s%s%s' % ( body_start, text, body_end ) # попарсить дерево tree = etree.parse( StringIO( u( text.encode( 'ascii', 'xmlcharrefreplace' ))), parser ) # будет не совсем красиво, зато ничего не сломается els = tree.xpath('span/div') + tree.xpath('i/div') + tree.xpath('b/div') for el in els: el.tag = 'span' # распечатать в unicode, иначе -- куча багов text = etree.tostring( tree, encoding='unicode', xml_declaration=False ) # вырезать оболочку <body>...</body> text = text.strip()[ len( body_start ) : -len( body_end ) ] return text
def determine_tone(pinyin): '''determine_tone(string) --> {0..4} detect tone of given pinyin word. return value: int from 0 up to 4, where 0 means that tone undetermined. ''' pinyin = u(pinyin) for letter in pinyin: if letter in _t1: return 1 if letter in _t2: return 2 if letter in _t3: return 3 if letter in _t4: return 4 # not found, fall-back to zero return 0
def colorized_HTML_string_from_string( string, pinyin_wrapper_class=PINYIN_WRAPPER_CLASS, tones_classes=TONES_CLASSES): '''colorized_HTML_string_from_string(string[, pinyin_wrapper_class][, tones_classes]) --> unicode !! replacing obsolete ``colorize_pin_yin``. detect and wrap pinyin with HTML in plain text *string*. if no pinyin found, string won't be modified and no wrapper applied. return value: string represents one HTML element <span> whose class is *pinyin_wrapper_class*. it contains child text nodes and inner <span>s with classes set according to contained pinyin tone. these classes can be specified by *tone_classes* argument. returns None if no pinyin found or all tones are zero. ''' string = u(string) ranges = ranges_of_pinyin_in_string(string) if not ranges: return None pinyin_wrapper_class = u(pinyin_wrapper_class) tones_classes = (u(tones_classes[0]), u(tones_classes[1]), u(tones_classes[2]), u(tones_classes[3]), u(tones_classes[4])) words = map(lambda r: r._slice(string), ranges) tones = map(determine_tone, words) if not any(tones): return None # all tones are zero, probably it is not pinyin. # do a colorize work here prev_end = 0 result = u'<span class="%s">' % pinyin_wrapper_class for range, word, tone in zip(ranges, words, tones): result += string[prev_end:range.location] # colorize one word result += u'<span class="{}">{}</span>'.format(tones_classes[tone], word) prev_end = range.location + range.length result += string[prev_end:] + u"</span>" return result
def step2(text): # обернуть text = u'%s%s%s' % (body_start, text, body_end) # попарсить дерево tree = etree.parse( StringIO(u(text.encode('ascii', 'xmlcharrefreplace'))), parser) # будет не совсем красиво, зато ничего не сломается els = tree.xpath('span/div') + tree.xpath('i/div') + tree.xpath( 'b/div') for el in els: el.tag = 'span' # распечатать в unicode, иначе -- куча багов text = etree.tostring(tree, encoding='unicode', xml_declaration=False) # вырезать оболочку <body>...</body> text = text.strip()[len(body_start):-len(body_end)] return text
def colorized_HTML_element_from_string( string, pinyin_wrapper_class=PINYIN_WRAPPER_CLASS, tones_classes=TONES_CLASSES): '''colorized_HTML_element_from_string(string[, pinyin_wrapper_class][, tones_classes]) --> etree.Element or *string* same as ``colorized_HTML_string_from_string``, but returns an ``etree.Element`` or None. ''' string = u(string) ranges = ranges_of_pinyin_in_string(string) if not ranges: return None pinyin_wrapper_class = u(pinyin_wrapper_class) tones_classes = (u(tones_classes[0]), u(tones_classes[1]), u(tones_classes[2]), u(tones_classes[3]), u(tones_classes[4])) # do a colorize work here words = map(lambda r: r._slice(string), ranges) tones = map(determine_tone, words) if not any(tones): return None # all tones are zero, probably it is not pinyin. import lxml.etree as ET prev_end = 0 wrapper = ET.Element("span") wrapper.set("class", pinyin_wrapper_class) wrapper.text = string[:ranges[0].location] for i, range in enumerate(ranges): word = range._slice(string) span = ET.SubElement(wrapper, "span") span.set("class", tones_classes[determine_tone(word)]) span.text = word if len(ranges) > i + 1: span.tail = string[range.location + range.length:ranges[i+1].location] span.tail = string[range.location + range.length:] return wrapper
def step1(): plain_replace_table = [ ( ur'\[', ur'[' ), ( ur'\]', ur']' ), # ( u'\n', u'<br/>' ), ( u'[b]', u'<b>' ), ( u'[/b]', u'</b>' ), ( u'[c][i]', u'[i][c]' ), ( u'[/i][/c]', u'[/c][/i]' ), ( u'[i]', u'<i>' ), ( u'[/i]', u'</i>' ), ( u'[c]', u'<span class="green">' ), ( u'[/c]', u'</span>' ), ( u'[e]', u'[ex]' ), ( u'[/e]', u'[/ex]' ), ( u'[ex]', u'<div class="e">' ), ( u'[/ex]', u'</div>' ), ( u'[/m]', u'</div>' ), ( u'[*]', u'<div class="sec">' ), ( u'[/*]', u'</div>' ), ( u'[p]', u'<i class="green">' ), ( u'[/p]', u'</i>' ), ( u'[com]', u'<div class="com">' ), ( u'[/com]', u'</div>' ), ( u'[trn]', u'<div class="trn">' ), ( u'[/trn]', u'</div>' ), ( u'[!trs]', u'<noindex>' ), ( u'[/!trs]', u'</noindex>' ), ( u'[sub]', u'<sub>' ), ( u'[/sub]', u'</sub>' ), ( u'[sup]', u'<sup>' ), ( u'[/sup]', u'</sup>' ) ] href_replace = lambda x: ur'<a href="%s">%s</a>' % ( # у uri своя кодировка, не xml entity # заменим только < и " etree \ .parse( StringIO( u'<a>%s</a>' % u( x.groups()[ 0 ] ) ) \ ) \ .getroot() \ .text \ .replace( u'<', u'%3C' ) \ .replace( u'"', u'%22' ), x.groups()[0] ) reg_sub_table = [ ( ur'\[c (.+?)\]', ur'<span style="color=\1">' ), ( ur'- \[ref\](.+?)\[\/ref\]', ur'<div class="m2">- [ref]\1[/ref]</div>' ), ( ur'\[ref\](.+?)\[\/ref\]', href_replace ), ( ur'\[url\](.+?)\[\/url\]', href_replace ), ( ur'\[m(\d)\]', ur'<div class="m\1">' ) ] # скомпилировать регулярки перед запуском reg_sub_table = map( lambda (r, s): ( re.compile( r, re.UNICODE ), s ), reg_sub_table ) def step1( text ): for old, new in plain_replace_table: text = text.replace( old, new ) for old, new in reg_sub_table: text = re.sub( old, new, text ) return text return step1
def testUFromBool(self): self.assertTypeEquals(u"True", u(True))
def testUFromAsciiString(self): self.assertTypeEquals(u"string", u("string"))
def spaces(s): """strip off leading and trailing whitespaces, and replace contiguous whitespaces with just one. """ return re.sub(spaces_re, u' ', u(s).strip())
def testUFromRichUnicode(self): self.assertTypeEquals(self.richuni, u(self.richuni))
# where x = m*d/1000 + c/1000. c is in mils and m is in mils per inch # of diameter. ("Shrink", 0.5, 1.5), ("Force", 0.5, 0.75), ("Drive", 0.3, 0.45), ("Push", -0.15, -0.35), ("Slide", -0.3, -0.45), ("Precision running", -0.5, -0.65), ("Close running", -0.6, -0.8), ("Normal running", -1.0, -1.5), ("Easy running", -1.5, -2.25), ("Small clearance", -2.0, -3.0), ("Large clearance", -3.0, -5.0), ) in2mm = u("inches") / u("mm") # Colors interference, clearance = color.lred, color.lgreen def Usage(d, status=1): path, name = os.path.split(sys.argv[0]) print(''' Usage: {name} diameter [unit] For a given diameter, print a table showing fits for both basic hole size and basic shaft size (here, "basic" means you've got the hole or shaft size you want and you want to calculate the size of the mating part to get a desired fit). The diameter is measured in inches by default. You can include a unit on the command line.
def dsl_to_html(text): return step2(step1(u(text).strip()))
def step1(): plain_replace_table = [ (ur'\[', ur'['), (ur'\]', ur']'), # ( u'\n', u'<br/>' ), (u'[b]', u'<b>'), (u'[/b]', u'</b>'), (u'[c][i]', u'[i][c]'), (u'[/i][/c]', u'[/c][/i]'), (u'[i]', u'<i>'), (u'[/i]', u'</i>'), (u'[c]', u'<span class="green">'), (u'[/c]', u'</span>'), (u'[e]', u'[ex]'), (u'[/e]', u'[/ex]'), (u'[ex]', u'<div class="e">'), (u'[/ex]', u'</div>'), (u'[/m]', u'</div>'), (u'[*]', u'<div class="sec">'), (u'[/*]', u'</div>'), (u'[p]', u'<i class="green">'), (u'[/p]', u'</i>'), (u'[com]', u'<div class="com">'), (u'[/com]', u'</div>'), (u'[trn]', u'<div class="trn">'), (u'[/trn]', u'</div>'), (u'[!trs]', u'<noindex>'), (u'[/!trs]', u'</noindex>'), (u'[sub]', u'<sub>'), (u'[/sub]', u'</sub>'), (u'[sup]', u'<sup>'), (u'[/sup]', u'</sup>') ] href_replace = lambda x: ur'<a href="%s">%s</a>' % ( # у uri своя кодировка, не xml entity # заменим только < и " etree \ .parse( StringIO( u'<a>%s</a>' % u( x.groups()[ 0 ] ) ) \ ) \ .getroot() \ .text \ .replace( u'<', u'%3C' ) \ .replace( u'"', u'%22' ), x.groups()[0] ) reg_sub_table = [(ur'\[c (.+?)\]', ur'<span style="color=\1">'), (ur'- \[ref\](.+?)\[\/ref\]', ur'<div class="m2">- [ref]\1[/ref]</div>'), (ur'\[ref\](.+?)\[\/ref\]', href_replace), (ur'\[url\](.+?)\[\/url\]', href_replace), (ur'\[m(\d)\]', ur'<div class="m\1">')] # скомпилировать регулярки перед запуском reg_sub_table = map(lambda (r, s): (re.compile(r, re.UNICODE), s), reg_sub_table) def step1(text): for old, new in plain_replace_table: text = text.replace(old, new) for old, new in reg_sub_table: text = re.sub(old, new, text) return text return step1
u'''бывать{(ся)} [m1]бывает ([c][i]прим.[/c] часто встречаются[/i])[/m] ''', u'''статья & ко тест <на> эскейпы & скобки''', u'''escapeXML здесь мы собираемся заменять символы '<', '>', '&' и '[b]"[/b]'. они будут заменены на '<', '>', '&' и '"' соответственно. ''', u''' проверка [m1][p]сущ.[/p] от [c][i]гл.[/c][/i] [b]проверять[/b][/m] [m1]1) тестирование[/m] [m2][ex][*]проверка на вшивость[/*][/ex][/m] ''', u'''加一点儿[汉语] [m1]为的是[ref]看一看[/ref]。[b]一见[/b]复杂的句子,就[ref]吓死[/ref]了。[/m] ''', u'''ссылки [m1]поведение [ref]"ссылок"[/ref] со специальными [url]& знаками[/url][/m] ''', u'''одинаковые ссылки [ref] "tt" [/ref] [ref] "dd" [/ref] [ref] "tt & dd" [/ref] [ref] "dd" & tt [/ref] ''', u'''R&D计划 r&d jìhuà [m1]программа, план исследований и разработок[/m] ''' ] for s in testing_entries: e.read(StringIO(s)) e.parse() print u'исходный:\n' + s + u'\nрезультат:\n' + u(e) + '\n\n'
def testUFromCallable(self): l = lambda x: x**2 self.assertTrue(u(l).startswith(u"<function <lambda> at 0x"))
def n2(x): # fastest while N > 1000 particles, ~1 ms for N=1000 x = x.reshape(-1, 3) x = x / np.linalg.norm(x, axis=1)[:, None] return u(x)
def testUFromAsciiUnicode(self): self.assertTypeEquals(u"string", u(u"string"))
def testUFromNumber(self): self.assertTypeEquals(u"14.5", u(14.5))
def testUFromRichString(self): self.assertTypeEquals(self.richuni, u(self.richstr))
def dsl_to_html( text ): return step2( step1( u( text ).strip() ))
они будут заменены на '<', '>', '&' и '"' соответственно. ''', u''' проверка [m1][p]сущ.[/p] от [c][i]гл.[/c][/i] [b]проверять[/b][/m] [m1]1) тестирование[/m] [m2][ex][*]проверка на вшивость[/*][/ex][/m] ''', u'''加一点儿[汉语] [m1]为的是[ref]看一看[/ref]。[b]一见[/b]复杂的句子,就[ref]吓死[/ref]了。[/m] ''', u'''ссылки [m1]поведение [ref]"ссылок"[/ref] со специальными [url]& знаками[/url][/m] ''', u'''одинаковые ссылки [ref] "tt" [/ref] [ref] "dd" [/ref] [ref] "tt & dd" [/ref] [ref] "dd" & tt [/ref] ''', u'''R&D计划 r&d jìhuà [m1]программа, план исследований и разработок[/m] ''' ] for s in testing_entries: e.read( StringIO( s ) ) e.parse() print u'исходный:\n' + s + u'\nрезультат:\n' + u( e ) + '\n\n'
import numpy as np import time from a import a from r import r from t import t_ciz as t from u import u from k import k a = a() r = r() t = t() u = u() k = k() iki_br = np.zeros((20, 3)) ataturk = np.column_stack((a, t, a, t, u, iki_br, r, k)) for i in range(20): for j in range(142): if ataturk[i][j] == 1: print('*', end='') else: print(' ', end='') print('') time.sleep(.100)