INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Feeds the network with an image: param image: image ( perhaps loaded with CV2 ): return: network result
def feed(self, image): """ Feeds the network with an image :param image: image (perhaps loaded with CV2) :return: network result """ network_name = self.__class__.__name__.lower() with tf.variable_scope(network_name): return self._feed(image)
Helper function: relinks soft symbolic link if necessary
def re_symlink(input_file, soft_link_name, log=None): """ Helper function: relinks soft symbolic link if necessary """ input_file = os.fspath(input_file) soft_link_name = os.fspath(soft_link_name) if log is None: prdebug = partial(print, file=sys.stderr) else: prdebug = log.d...
Intentionally racy test if target is writable.
def is_file_writable(test_file): """Intentionally racy test if target is writable. We intend to write to the output file if and only if we succeed and can replace it atomically. Before doing the OCR work, make sure the location is writable. """ p = Path(test_file) if p.is_symlink(): ...
Create a Postscript pdfmark file for Ghostscript PDF/ A conversion
def generate_pdfa_ps(target_filename, icc='sRGB'): """Create a Postscript pdfmark file for Ghostscript PDF/A conversion A pdfmark file is a small Postscript program that provides some information Ghostscript needs to perform PDF/A conversion. The only information we put in specifies that we want the fi...
Determines if the file claims to be PDF/ A compliant
def file_claims_pdfa(filename): """Determines if the file claims to be PDF/A compliant This only checks if the XMP metadata contains a PDF/A marker. It does not do full PDF/A validation. """ with pikepdf.open(filename) as pdf: pdfmeta = pdf.open_metadata() if not pdfmeta.pdfa_statu...
Fix pdfminer s name2unicode function
def name2unicode(name): """Fix pdfminer's name2unicode function Font cids that are mapped to names of the form /g123 seem to be, by convention characters with no corresponding Unicode entry. These can be subsetted fonts or symbolic fonts. There seems to be no way to map /g123 fonts to Unicode, barr...
Check if characters can be combined into a textline
def is_compatible(self, obj): """Check if characters can be combined into a textline We consider characters compatible if: - the Unicode mapping is known, and both have the same render mode - the Unicode mapping is unknown but both are part of the same font """ b...
Destroy some cdata
def _destroy(cls, cdata): """Destroy some cdata""" # Leptonica API uses double-pointers for its destroy APIs to prevent # dangling pointers. This means we need to put our single pointer, # cdata, in a temporary CDATA**. pp = ffi.new('{} **'.format(cls.LEPTONICA_TYPENAME), cdata) ...
iPython display hook
def _repr_png_(self): """iPython display hook returns png version of image """ data = ffi.new('l_uint8 **') size = ffi.new('size_t *') err = lept.pixWriteMemPng(data, size, self._cdata, 0) if err != 0: raise LeptonicaIOError("pixWriteMemPng") ...
Load an image file into a PIX object.
def open(cls, path): """Load an image file into a PIX object. Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If loading fails then the object will wrap a C null pointer. """ filename = fspath(path) with _LeptonicaErrorTrap(): return cls(lept.pi...
Write pix to the filename with the extension indicating format.
def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0): """Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive) """ fil...
Create a copy of a PIL. Image from this Pix
def frompil(self, pillow_image): """Create a copy of a PIL.Image from this Pix""" bio = BytesIO() pillow_image.save(bio, format='png', compress_level=1) py_buffer = bio.getbuffer() c_buffer = ffi.from_buffer(py_buffer) with _LeptonicaErrorTrap(): pix = Pix(lep...
Returns a PIL. Image version of this Pix
def topil(self): """Returns a PIL.Image version of this Pix""" from PIL import Image # Leptonica manages data in words, so it implicitly does an endian # swap. Tell Pillow about this when it reads the data. pix = self if sys.byteorder == 'little': if self.mo...
Returns the deskewed pix object.
def deskew(self, reduction_factor=0): """Returns the deskewed pix object. A clone of the original is returned when the algorithm cannot find a skew angle with sufficient confidence. reduction_factor -- amount to downsample (0 for default) when searching for skew angle ...
Returns the pix object rescaled according to the proportions given.
def scale(self, scale_xy): "Returns the pix object rescaled according to the proportions given." with _LeptonicaErrorTrap(): return Pix(lept.pixScale(self._cdata, scale_xy[0], scale_xy[1]))
Orthographic rotation quads: 0 - 3 number of clockwise rotations
def rotate_orth(self, quads): "Orthographic rotation, quads: 0-3, number of clockwise rotations" with _LeptonicaErrorTrap(): return Pix(lept.pixRotateOrth(self._cdata, quads))
Returns a tuple ( deskew angle in degrees confidence value ).
def find_skew(self): """Returns a tuple (deskew angle in degrees, confidence value). Returns (None, None) if no angle is available. """ with _LeptonicaErrorTrap(): angle = ffi.new('float *', 0.0) confidence = ffi.new('float *', 0.0) result = lept.pixF...
Remove a palette ( colormap ) ; if no colormap returns a copy of this image
def remove_colormap(self, removal_type): """Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* """ with _LeptonicaErrorTrap(): return Pix( lept.pixRemoveColormapGeneral(self._cdata, ...
Convert to PDF data with transcoding
def generate_pdf_ci_data(self, type_, quality): "Convert to PDF data, with transcoding" p_compdata = ffi.new('L_COMP_DATA **') result = lept.pixGenerateCIData(self._cdata, type_, quality, 0, p_compdata) if result != 0: raise LeptonicaError("Generate PDF data failed") ...
Open compressed data without transcoding
def open(cls, path, jpeg_quality=75): "Open compressed data, without transcoding" filename = fspath(path) p_compdata = ffi.new('L_COMP_DATA **') result = lept.l_generateCIDataForPdf( os.fsencode(filename), ffi.NULL, jpeg_quality, p_compdata ) if result != 0: ...
Returns palette pre - formatted for use in PDF
def get_palette_pdf_string(self): "Returns palette pre-formatted for use in PDF" buflen = len('< ') + len(' rrggbb') * self._cdata.ncolors + len('>') buf = ffi.buffer(self._cdata.cmapdatahex, buflen) return bytes(buf)
Update this page s fonts with a reference to the Glyphless font
def _update_page_resources(*, page, font, font_key, procset): """Update this page's fonts with a reference to the Glyphless font""" if '/Resources' not in page: page['/Resources'] = pikepdf.Dictionary({}) resources = page['/Resources'] try: fonts = resources['/Font'] except KeyError...
Insert the text layer from text page 0 on to pdf_base at page_num
def _weave_layers_graft( *, pdf_base, page_num, text, font, font_key, procset, rotation, strip_old_text, log ): """Insert the text layer from text page 0 on to pdf_base at page_num""" log.debug("Grafting") if Path(text).stat().st_size == 0: return # This is a pointer indicating a specific ...
Copy a font from the filename text into pdf_base
def _find_font(text, pdf_base): """Copy a font from the filename text into pdf_base""" font, font_key = None, None possible_font_names = ('/f-0-0', '/F1') try: with pikepdf.open(text) as pdf_text: try: pdf_text_fonts = pdf_text.pages[0].Resources.get('/Font', {}) ...
Walk the table of contents calling visitor_fn () at each node
def _traverse_toc(pdf_base, visitor_fn, log): """ Walk the table of contents, calling visitor_fn() at each node The /Outlines data structure is a messy data structure, but rather than navigating hierarchically we just track unique nodes. Enqueue nodes when we find them, and never visit them again....
Repair the table of contents
def _fix_toc(pdf_base, pageref_remap, log): """Repair the table of contents Whenever we replace a page wholesale, it gets assigned a new objgen number and other references to it within the PDF become invalid, most notably in the table of contents (/Outlines in PDF-speak). In weave_layers we collect ...
Apply text layer and/ or image layer changes to baseline file
def weave_layers(infiles, output_file, log, context): """Apply text layer and/or image layer changes to baseline file This is where the magic happens. infiles will be the main PDF to modify, and optional .text.pdf and .image-layer.pdf files, organized however ruffus organizes them. From .text.pdf,...
Validator for numeric params
def numeric(basetype, min_=None, max_=None): """Validator for numeric params""" min_ = basetype(min_) if min_ is not None else None max_ = basetype(max_) if max_ is not None else None def _numeric(string): value = basetype(string) if min_ is not None and value < min_ or max_ is not None...
Replace the elaborate ruffus stack trace with a user friendly description of the error message that occurred.
def do_ruffus_exception(ruffus_five_tuple, options, log): """Replace the elaborate ruffus stack trace with a user friendly description of the error message that occurred.""" exit_code = None _task_name, _job_name, exc_name, exc_value, exc_stack = ruffus_five_tuple if isinstance(exc_name, type): ...
Traverse a RethrownJobError and output the exceptions
def traverse_ruffus_exception(exceptions, options, log): """Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with ...
Work around Python issue with multiprocessing forking on closed streams
def check_closed_streams(options): """Work around Python issue with multiprocessing forking on closed streams https://bugs.python.org/issue28326 Attempting to a fork/exec a new Python process when any of std{in,out,err} are closed or not flushable for some reason may raise an exception. Fix this b...
Try to find version signature at start of file.
def _pdf_guess_version(input_file, search_window=1024): """Try to find version signature at start of file. Not robust enough to deal with appended files. Returns empty string if not found, indicating file is probably not PDF. """ with open(input_file, 'rb') as f: signature = f.read(search...
Get zero - based page info implied by filename e. g. 000002. pdf - > 1
def get_pageinfo(input_file, context): "Get zero-based page info implied by filename, e.g. 000002.pdf -> 1" pageno = page_number(input_file) - 1 pageinfo = context.get_pdfinfo()[pageno] return pageinfo
Get the DPI when nonsquare DPI is tolerable
def get_page_dpi(pageinfo, options): "Get the DPI when nonsquare DPI is tolerable" xres = max( pageinfo.xres or VECTOR_PAGE_DPI, options.oversample or 0, VECTOR_PAGE_DPI if pageinfo.has_vector else 0, ) yres = max( pageinfo.yres or VECTOR_PAGE_DPI, options.oversam...
Get the DPI when we require xres == yres scaled to physical units
def get_page_square_dpi(pageinfo, options): "Get the DPI when we require xres == yres, scaled to physical units" xres = pageinfo.xres or 0 yres = pageinfo.yres or 0 userunit = pageinfo.userunit or 1 return float( max( (xres * userunit) or VECTOR_PAGE_DPI, (yres * user...
Get the DPI when we require xres == yres in Postscript units
def get_canvas_square_dpi(pageinfo, options): """Get the DPI when we require xres == yres, in Postscript units""" return float( max( (pageinfo.xres) or VECTOR_PAGE_DPI, (pageinfo.yres) or VECTOR_PAGE_DPI, VECTOR_PAGE_DPI if pageinfo.has_vector else 0, opti...
Work out orientation correct for each page.
def orient_page(infiles, output_file, log, context): """ Work out orientation correct for each page. We ask Ghostscript to draw a preview page, which will rasterize with the current /Rotate applied, and then ask Tesseract which way the page is oriented. If the value of /Rotate is correct (e.g., a u...
Select the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.
def select_ocr_image(infiles, output_file, log, context): """Select the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.""" image = infiles[0] options = context.get_options() pageinfo = get_pageinfo(image, co...
Selects a whole page image that we can show the user ( if necessary )
def select_visible_page_image(infiles, output_file, log, context): """Selects a whole page image that we can show the user (if necessary)""" options = context.get_options() if options.clean_final: image_suffix = '.pp-clean.png' elif options.deskew: image_suffix = '.pp-deskew.png' el...
Selects the image layer for the output page. If possible this is the orientation - corrected input page or an image of the whole page converted to PDF.
def select_image_layer(infiles, output_file, log, context): """Selects the image layer for the output page. If possible this is the orientation-corrected input page, or an image of the whole page converted to PDF.""" options = context.get_options() page_pdf = next(ii for ii in infiles if ii.endswit...
Convert runs of qQ s in the stack into single graphobjs
def _normalize_stack(graphobjs): """Convert runs of qQ's in the stack into single graphobjs""" for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q for char in operator: # Split into individual ...
Interpret the PDF content stream.
def _interpret_contents(contentstream, initial_shorthand=UNIT_SQUARE): """Interpret the PDF content stream. The stack represents the state of the PDF graphics stack. We are only interested in the current transformation matrix (CTM) so we only track this object; a full implementation would need to trac...
Given the transformation matrix and image size find the image DPI.
def _get_dpi(ctm_shorthand, image_size): """Given the transformation matrix and image size, find the image DPI. PDFs do not include image resolution information within image data. Instead, the PDF page content stream describes the location where the image will be rasterized, and the effective resolutio...
Find inline images in the contentstream
def _find_inline_images(contentsinfo): "Find inline images in the contentstream" for n, inline in enumerate(contentsinfo.inline_images): yield ImageInfo( name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline )
Search for all XObject - based images in the container
def _image_xobjects(container): """Search for all XObject-based images in the container Usually the container is a page, but it could also be a Form XObject that contains images. Filter out the Form XObjects which are dealt with elsewhere. Generate a sequence of tuples (image, xobj container), whe...
Find images stored in the container s/ Resources/ XObject
def _find_regular_images(container, contentsinfo): """Find images stored in the container's /Resources /XObject Usually the container is a page, but it could also be a Form XObject that contains images. Generates images with their DPI at time of drawing. """ for pdfimage, xobj in _image_xobje...
Find any images that are in Form XObjects in the container
def _find_form_xobject_images(pdf, container, contentsinfo): """Find any images that are in Form XObjects in the container The container may be a page, or a parent Form XObject. """ if '/Resources' not in container: return resources = container['/Resources'] if '/XObject' not in resour...
Find all individual instances of images drawn in the container
def _process_content_streams(*, pdf, container, shorthand=None): """Find all individual instances of images drawn in the container Usually the container is a page, but it may also be a Form XObject. On a typical page images are stored inline or as regular images in an XObject. Form XObjects may i...
Smarter text detection that ignores text in margins
def _page_has_text(text_blocks, page_width, page_height): """Smarter text detection that ignores text in margins""" pw, ph = float(page_width), float(page_height) margin_ratio = 0.125 interior_bbox = ( margin_ratio * pw, # left (1 - margin_ratio) * ph, # top (1 - margin_ratio...
Extract only limited content from text boxes
def simplify_textboxes(miner, textbox_getter): """Extract only limited content from text boxes We do this to save memory and ensure that our objects are pickleable. """ for box in textbox_getter(miner): first_line = box._objs[0] first_char = first_line._objs[0] visible = first_...
Get text boxes out of Ghostscript txtwrite xml
def page_get_textblocks(infile, pageno, xmltext, height): """Get text boxes out of Ghostscript txtwrite xml""" root = xmltext if not hasattr(xmltext, 'findall'): return [] def blocks(): for span in root.findall('.//span'): bbox_str = span.attrib['bbox'] font_siz...
Does Tesseract have textonly_pdf capability?
def has_textonly_pdf(): """Does Tesseract have textonly_pdf capability? Available in v4.00.00alpha since January 2017. Best to parse the parameter list """ args_tess = ['tesseract', '--print-parameters', 'pdf'] params = '' try: params = check_output(args_tess, universal_newlines=Tru...
Produce a. hocr file that reports no text detected on a page that is the same size as the input image.
def _generate_null_hocr(output_hocr, output_sidecar, image): """Produce a .hocr file that reports no text detected on a page that is the same size as the input image.""" from PIL import Image im = Image.open(image) w, h = im.size with open(output_hocr, 'w', encoding="utf-8") as f: f.wr...
Use Tesseract to render a PDF.
def generate_pdf( *, input_image, skip_pdf=None, output_pdf, output_text, language: list, engine_mode, text_only: bool, tessconfig: list, timeout: float, pagesegmode: int, user_words, user_patterns, log, ): '''Use Tesseract to render a PDF. input_image --...
Extract image using extract_fn
def extract_images(pike, root, log, options, extract_fn): """Extract image using extract_fn Enumerate images on each page, lookup their xref/ID number in the PDF. Exclude images that are soft masks (i.e. alpha transparency related). Record the page number on which an image is first used, since images m...
Extract any > = 2bpp image we think we can improve
def extract_images_generic(pike, root, log, options): """Extract any >=2bpp image we think we can improve""" jpegs = [] pngs = [] for _, xref, ext in extract_images(pike, root, log, options, extract_image_generic): log.debug('xref = %s ext = %s', xref, ext) if ext == '.png': ...
Extract any bitonal image that we think we can improve as JBIG2
def extract_images_jbig2(pike, root, log, options): """Extract any bitonal image that we think we can improve as JBIG2""" jbig2_groups = defaultdict(list) for pageno, xref, ext in extract_images( pike, root, log, options, extract_image_jbig2 ): group = pageno // options.jbig2_page_group...
Produce JBIG2 images from their groups
def _produce_jbig2_images(jbig2_groups, root, log, options): """Produce JBIG2 images from their groups""" def jbig2_group_futures(executor, root, groups): for group, xref_exts in groups.items(): prefix = f'group{group:08d}' future = executor.submit( jbig2enc.conv...
Convert images to JBIG2 and insert into PDF.
def convert_to_jbig2(pike, jbig2_groups, root, log, options): """Convert images to JBIG2 and insert into PDF. When the JBIG2 page group size is > 1 we do several JBIG2 images at once and build a symbol dictionary that will span several pages. Each JBIG2 image must reference to its symbol dictionary. If...
Get the version of the specified program
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'): "Get the version of the specified program" args_prog = [program, version_arg] try: proc = run( args_prog, close_fds=True, universal_newlines=True, stdout=PIPE, st...
Return the textual content of the element and its children
def _get_element_text(self, element): """ Return the textual content of the element and its children """ text = '' if element.text is not None: text += element.text for child in element.getchildren(): text += self._get_element_text(child) i...
Returns a tuple containing the coordinates of the bounding box around an element
def element_coordinates(cls, element): """ Returns a tuple containing the coordinates of the bounding box around an element """ out = (0, 0, 0, 0) if 'title' in element.attrib: matches = cls.box_pattern.search(element.attrib['title']) if matches: ...
Returns a tuple containing the baseline slope and intercept.
def baseline(cls, element): """ Returns a tuple containing the baseline slope and intercept. """ if 'title' in element.attrib: matches = cls.baseline_pattern.search(element.attrib['title']) if matches: return float(matches.group(1)), int(matches.gr...
Returns the quantity in PDF units ( pt ) given quantity in pixels
def pt_from_pixel(self, pxl): """ Returns the quantity in PDF units (pt) given quantity in pixels """ return Rect._make((c / self.dpi * inch) for c in pxl)
Creates a PDF file with an image superimposed on top of the text. Text is positioned according to the bounding box of the lines in the hOCR file. The image need not be identical to the image used to create the hOCR file. It can have a lower resolution different color mode etc.
def to_pdf( self, outFileName, imageFileName=None, showBoundingboxes=False, fontname="Helvetica", invisibleText=False, interwordSpaces=False, ): """ Creates a PDF file with an image superimposed on top of the text. Text is positioned ac...
Use the txtwrite device to get text layout information out
def extract_text(input_file, pageno=1): """Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size=".....
Rasterize one page of a PDF at resolution ( xres yres ) in canvas units.
def rasterize_pdf( input_file, output_file, xres, yres, raster_device, log, pageno=1, page_dpi=None, rotation=None, filter_vector=False, ): """Rasterize one page of a PDF at resolution (xres, yres) in canvas units. The image is sized to match the integer pixels dimension...
Generate a PDF/ A.
def generate_pdfa( pdf_pages, output_file, compression, log, threads=1, pdf_version='1.5', pdfa_part='2', ): """Generate a PDF/A. The pdf_pages, a list files, will be merged into output_file. One or more PDF files may be merged. One of the files in this list must be a pdfmark ...
零声母转换,还原原始的韵母
def convert_zero_consonant(pinyin): """零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。 """ ...
ü 转换,还原原始的韵母
def convert_uv(pinyin): """ü 转换,还原原始的韵母 ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚), ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 """ return UV_RE.sub( lambda m: ''.join((m.group(1), UV_MAP[m.group(2)], m.group(3))), pinyin)
iou 转换,还原原始的韵母
def convert_iou(pinyin): """iou 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return IU_RE.sub(lambda m: m.group(1) + IU_MAP[m.group(2)], pinyin)
uei 转换,还原原始的韵母
def convert_uei(pinyin): """uei 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return UI_RE.sub(lambda m: m.group(1) + UI_MAP[m.group(2)], pinyin)
uen 转换,还原原始的韵母
def convert_uen(pinyin): """uen 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return UN_RE.sub(lambda m: m.group(1) + UN_MAP[m.group(2)], pinyin)
还原原始的韵母
def convert_finals(pinyin): """还原原始的韵母""" pinyin = convert_zero_consonant(pinyin) pinyin = convert_uv(pinyin) pinyin = convert_iou(pinyin) pinyin = convert_uei(pinyin) pinyin = convert_uen(pinyin) return pinyin
按是否是汉字进行分词
def _seg(chars): """按是否是汉字进行分词""" s = '' # 保存一个词 ret = [] # 分词结果 flag = 0 # 上一个字符是什么? 0: 汉字, 1: 不是汉字 for n, c in enumerate(chars): if RE_HANS.match(c): # 汉字, 确定 flag 的初始值 if n == 0: # 第一个字符 flag = 0 if flag == 0: s += c ...
将传入的字符串按是否是汉字来分割
def simple_seg(hans): """将传入的字符串按是否是汉字来分割""" assert not isinstance(hans, bytes_type), \ 'must be unicode string or [unicode, ...] list' if isinstance(hans, text_type): return _seg(hans) else: hans = list(hans) if len(hans) == 1: return simple_seg(hans[0]) ...
载入用户自定义的单字拼音库
def load_single_dict(pinyin_dict, style='default'): """载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}`` :param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type pinyin_dict: dict """ if style == 'tone2': for k, v in pinyin_dict.items(): v = _replace_t...
载入用户自定义的词语拼音库
def load_phrases_dict(phrases_dict, style='default'): """载入用户自定义的词语拼音库 :param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}`` :param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type phrases_dict: dict """ if style == 'tone2': for k, value in phrases_dict.items(): ...
根据拼音风格格式化带声调的拼音.
def to_fixed(pinyin, style, strict=True): """根据拼音风格格式化带声调的拼音. :param pinyin: 单个拼音 :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 根据拼音风格格式化后的拼音字符串 :rtype: unicode """ return convert_style(pinyin, style=style, strict=strict, default=pinyin)
处理没有拼音的字符
def _handle_nopinyin_char(chars, errors='default'): """处理没有拼音的字符""" if callable_check(errors): return errors(chars) if errors == 'default': return chars elif errors == 'ignore': return None elif errors == 'replace': if len(chars) > 1: return ''.join(text_...
单字拼音转换.
def single_pinyin(han, style, heteronym, errors='default', strict=True): """单字拼音转换. :param han: 单个汉字 :param errors: 指定如何处理没有拼音的字符,详情请参考 :py:func:`~pypinyin.pinyin` :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 返回拼音列表,多音字会有多个拼音项 :rtype: list """ num = ord(han) # 处...
词语拼音转换.
def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True): """词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 拼音列表 :rtype: list """ py = [] if phrase in PHRASES_DICT: py = deepcopy(PHRASES_DICT[phrase]) ...
: param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符, 不存在混合的情况。
def _pinyin(words, style, heteronym, errors, strict=True): """ :param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符, 不存在混合的情况。 """ pys = [] # 初步过滤没有拼音的字符 if RE_HANS.match(words): pys = phrase_pinyin(words, style=style, heteronym=heteronym, errors=error...
将汉字转换为拼音.
def pinyin(hans, style=Style.TONE, heteronym=False, errors='default', strict=True): """将汉字转换为拼音. :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ). 可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。 :type hans: unicode 字符串或字符串列表 :param style: 指定拼音风格,默认是 :p...
生成 slug 字符串.
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-', errors='default', strict=True): """生成 slug 字符串. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~pypinyin.Style` :param heteronym...
不包含多音字的拼音列表.
def lazy_pinyin(hans, style=Style.NORMAL, errors='default', strict=True): """不包含多音字的拼音列表. 与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串, 并且每个字只包含一个读音. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~p...
根据拼音风格把原始拼音转换为不同的格式
def convert(pinyin, style, strict, default=None, **kwargs): """根据拼音风格把原始拼音转换为不同的格式 :param pinyin: 原始有声调的单个拼音 :type pinyin: unicode :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict` :type strict: bool :param default: 拼音风格对应的实现不存在时返回的默认值 :return: 按照拼音风格进行处理过后的拼音字符串...
注册一个拼音风格实现
def register(style, func=None): """注册一个拼音风格实现 :: @register('echo') def echo(pinyin, **kwargs): return pinyin # or register('echo', echo) """ if func is not None: _registry[style] = func return def decorator(func): _registry[styl...
获取单个拼音中的声母.
def get_initials(pinyin, strict): """获取单个拼音中的声母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 声母 :rtype: unicode """ if strict: _initials = _INITIALS else: _initials = _INITIALS_NOT_STRICT for i in _initials: i...
获取单个拼音中的韵母.
def get_finals(pinyin, strict): """获取单个拼音中的韵母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 韵母 :rtype: unicode """ if strict: pinyin = convert_finals(pinyin) initials = get_initials(pinyin, strict=strict) or '' # 没有声母,整个都是韵母 ...
把声调替换为数字
def replace_symbol_to_number(pinyin): """把声调替换为数字""" def _replace(match): symbol = match.group(0) # 带声调的字符 # 返回使用数字标识声调的字符 return PHONETIC_SYMBOL_DICT[symbol] # 替换拼音中的带声调字符 return RE_PHONETIC_SYMBOL.sub(_replace, pinyin)
把带声调字符替换为没有声调的字符
def replace_symbol_to_no_symbol(pinyin): """把带声调字符替换为没有声调的字符""" def _replace(match): symbol = match.group(0) # 带声调的字符 # 去掉声调: a1 -> a return RE_NUMBER.sub(r'', PHONETIC_SYMBOL_DICT[symbol]) # 替换拼音中的带声调字符 return RE_PHONETIC_SYMBOL.sub(_replace, pinyin)
分词
def cut(self, text): """分词 :param text: 待分词的文本 :yield: 单个词语 """ remain = text while remain: matched = '' # 一次加一个字的匹配 for index in range(len(remain)): word = remain[:index + 1] if word in self._prefix_set...
更新 prefix set
def train(self, word_s): """更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None """ for word in word_s: # 把词语的每个前缀更新到 prefix_set 中 for index in range(len(word)): self._set.add(word[:index + 1])
0 汉字 1 英文字母 2. 数字 3. 其他
def get_char_type(ch): """ 0, 汉字 1, 英文字母 2. 数字 3. 其他 """ if re.match(en_p, ch): return 1 elif re.match("\d+", ch): return 2 elif re.match(re_han, ch): return 3 else: return 4
Translates a given pyquil Program to a TikZ picture in a Latex document.
def to_latex(circuit, settings=None): """ Translates a given pyquil Program to a TikZ picture in a Latex document. :param Program circuit: The circuit to be drawn, represented as a pyquil program. :param dict settings: An optional dictionary with settings for drawing the circuit. See `get_default_setti...
Return the body of the Latex document including the entire circuit in TikZ format.
def body(circuit, settings): """ Return the body of the Latex document, including the entire circuit in TikZ format. :param Program circuit: The circuit to be drawn, represented as a pyquil program. :param dict settings: :return: Latex string to draw the entire circuit. :rtype: string ...
Generate the TikZ code for one line of the circuit up to a certain gate.
def to_tikz(self, line, circuit, end=None): """ Generate the TikZ code for one line of the circuit up to a certain gate. It modifies the circuit to include only the gates which have not been drawn. It automatically switches to other lines if the gates on those lines have...
Return the string representation of the gate.
def _gate_name(self, gate): """ Return the string representation of the gate. Tries to use gate.tex_str and, if that is not available, uses str(gate) instead. :param string gate: Gate object of which to get the name / LaTeX representation. :return: LaTeX gate name. ...
Return the TikZ code for a Swap - gate.
def _swap_gate(self, lines, ctrl_lines): """ Return the TikZ code for a Swap-gate. :param lines: List of length 2 denoting the target qubit of the Swap gate. :type: list[int] :param ctrl_lines: List of qubit lines which act as controls. :type: list[int] """ ...