text
stringlengths
81
112k
Register Flasgger views def register_views(self, app): """ Register Flasgger views """ # Wrap the views in an arbitrary number of decorators. def wrap_view(view): if self.decorators: for decorator in self.decorators: view = decora...
Inject headers after request def add_headers(self, app): """ Inject headers after request """ @app.after_request def after_request(response): # noqa for header, value in self.config.get('headers'): response.headers[header] = value return ...
A decorator that is used to validate incoming requests data against a schema swagger = Swagger(app) @app.route('/pets', methods=['POST']) @swagger.validate('Pet') @swag_from("pet_post_endpoint.yml") def post(): return db.insert(reques...
This method finds a schema known to Flasgger and returns it. :raise KeyError: when the specified :param schema_id: is not found by Flasgger :param schema_id: the id of the desired schema def get_schema(self, schema_id): """ This method finds a schema known to Flasgger and retu...
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' - in: path name: todo_id required: true description: The ID of the task, try 42! ...
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' responses: 201: description: The task has been created schema: $ref: '#/de...
Example endpoint return a list of colors by palette This is using docstring for specifications --- tags: - colors parameters: - name: palette in: path type: string enum: ['all', 'rgb', 'cmyk'] required: true default: all description: Which pale...
Decorator to require HTTP Basic Auth for your endpoint. def requires_basic_auth(f): """Decorator to require HTTP Basic Auth for your endpoint.""" def check_auth(username, password): return username == "guest" and password == "secret" def authenticate(): return Response( "Authe...
Scales the image to a given scale. :param image: :param scale: :return: def __scale_image(image, scale: float): """ Scales the image to a given scale. :param image: :param scale: :return: """ height, width, _ = image.shape width_s...
Non Maximum Suppression. :param boxes: np array with bounding boxes. :param threshold: :param method: NMS method to apply. Available values ('Min', 'Union') :return: def __nms(boxes, threshold, method): """ Non Maximum Suppression. :param boxes: np array with b...
Detects bounding boxes from the specified image. :param img: image to process :return: list containing all the bounding boxes detected with their keypoints. def detect_faces(self, img) -> list: """ Detects bounding boxes from the specified image. :param img: image to process ...
First stage of the MTCNN. :param image: :param scales: :param stage_status: :return: def __stage1(self, image, scales: list, stage_status: StageStatus): """ First stage of the MTCNN. :param image: :param scales: :param stage_status: :retur...
Second stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return: def __stage2(self, img, total_boxes, stage_status:StageStatus): """ Second stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :r...
Third stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return: def __stage3(self, img, total_boxes, stage_status: StageStatus): """ Third stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :...
Creates a tensorflow variable with the given name and shape. :param name: name to set for the variable. :param shape: list defining the shape of the variable. :return: created TF variable. def __make_var(self, name: str, shape: list): """ Creates a tensorflow variable with the g...
Creates a feed layer. This is usually the first layer in the network. :param name: name of the layer :return: def new_feed(self, name: str, layer_shape: tuple): """ Creates a feed layer. This is usually the first layer in the network. :param name: name of the layer :retu...
Creates a convolution layer for the network. :param name: name for the layer :param kernel_size: tuple containing the size of the kernel (Width, Height) :param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size. :param stride_size: tuple containing ...
Creates a new prelu layer with the given name and input. :param name: name for this layer. :param input_layer_name: name of the layer that serves as input for this one. def new_prelu(self, name: str, input_layer_name: str=None): """ Creates a new prelu layer with the given name and inpu...
Creates a new max pooling layer. :param name: name for the layer. :param kernel_size: tuple containing the size of the kernel (Width, Height) :param stride_size: tuple containing the size of the stride (Width, Height) :param padding: Type of padding. Available values are: ('SAME', 'VALID...
Creates a new fully connected layer. :param name: name for the layer. :param output_count: number of outputs of the fully connected layer. :param relu: boolean flag to set if ReLu should be applied at the end of this layer. :param input_layer_name: name of the input layer for this layer...
Creates a new softmax layer :param name: name to set for the layer :param axis: :param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of the network. def new_softmax(self, name, axis, input_layer_name: str=None): """ ...
Adds a layer to the network. :param name: name of the layer to add :param layer_output: output layer. def add_layer(self, name: str, layer_output): """ Adds a layer to the network. :param name: name of the layer to add :param layer_output: output layer. """ ...
Retrieves the layer by its name. :param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the network. :return: layer output def get_layer(self, name: str=None): """ Retrieves the layer by its name. :param name: name of the la...
Sets the weights values of the network. :param weights_values: dictionary with weights for each layer def set_weights(self, weights_values: dict, ignore_missing=False): """ Sets the weights values of the network. :param weights_values: dictionary with weights for each layer """ ...
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....
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...
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. def is_file_writable(test_file): """Intentionally racy test if target is writable. We intend...
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 file to be a PDF/A, and we want to Ghostscript to conver...
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. 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. ...
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, barring a ToUnicode data structure....
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 def is_compatible(self, obj): """Check if characters ...
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.LEPTONIC...
iPython display hook returns png version of image 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:...
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. def open(cls, path): """Load an image file into a PIX object. Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. ...
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) def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0): """Write pix to the filen...
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 _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.byte...
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 def deskew(self, reduction_factor=0): """Retu...
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). Returns (None, None) if no angle is available. def find_skew(self): """Returns a tuple (deskew angle in degrees, confidence value). Returns (None, None) if no angle is available. """ with _LeptonicaErrorTrap(): ...
Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* 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_CM...
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 LeptonicaErr...
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_...
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'...
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 =...
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 ...
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. set() is awesome. We look for the two types of obje...
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 pageref_remap, a mapping that describes the new o...
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, we copy the content stream (which contains the Tesseract ...
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 va...
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 ...
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 exception marshalling that would give different output wheth...
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 by opening devnull if the handle seems to b...
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. def _pdf_guess_version(input_file, search_window=1024): """Try to find version signature at start of file. Not robust enough to deal ...
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.yre...
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( ...
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, ...
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 user already manually fixed rotation), then Tesseract will say...
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 preproc...
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' ...
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-correcte...
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 ...
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 track many other items. The CTM is initialized to the mapping from user space...
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 resolution is the ratio of the pixel size to raster t...
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 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), where container, where xobj is the nam...
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. def _find_regular_images(container, contentsinfo): """Find images stored in the container's /Resourc...
Find any images that are in Form XObjects in the container The container may be a page, or a parent Form XObject. 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. """ ...
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 include inline images, XObject images, and recursively, other Form XO...
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 -...
Extract only limited content from text boxes We do this to save memory and ensure that our objects are pickleable. 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 te...
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'): bbo...
Does Tesseract have textonly_pdf capability? Available in v4.00.00alpha since January 2017. Best to parse the parameter list 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_tes...
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 ...
Use Tesseract to render a PDF. input_image -- image to analyze skip_pdf -- if we time out, use this file as output output_pdf -- file to generate output_text -- OCR text file language -- list of languages to consider engine_mode -- engine mode argument for tess v4 text_only -- enable tesser...
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 may be used on multiple pages (or multiple times on the same p...
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'...
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_imag...
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 = execut...
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 too many pages shared the same dictionary JBIG2 encoding becomes...
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=Tru...
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():...
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: ...
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: ...
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. ...
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="..."> <char bbox="...." c="X"/> :param p...
Rasterize one page of a PDF at resolution (xres, yres) in canvas units. The image is sized to match the integer pixels dimensions implied by (xres, yres) even if those numbers are noninteger. The image's DPI will be overridden with the values in page_dpi. :param input_file: pathlike :param output...
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 file that provides Ghostscript with details on how to perform the PDF/A conversion. By default with we pick PDF/A-2b, but this works for 1...
零声母转换,还原原始的韵母 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_zero_consonant(pinyin): """零声母转换,还原...
ü 转换,还原原始的韵母 ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚), ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 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.g...
iou 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 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 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 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 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 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 +=...
将传入的字符串按是否是汉字来分割 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 simpl...