def test_drop_apostrophe(self): self.assertEqual(trans.pinyin_to_zhuyin("xi1'an1"), "ㄒㄧ ㄢ") self.assertEqual(trans.pinyin_to_ipa("xi1'an1"), "ɕi˥ an˥") self.assertEqual(trans.to_pinyin("xi1'an1"), "xī'ān") self.assertEqual(trans.pinyin_to_zhuyin("xī'ān"), "ㄒㄧ ㄢ") self.assertEqual(trans.pinyin_to_ipa("xī'ān"), "ɕi˥ an˥") self.assertEqual(trans.to_pinyin("xī'ān", accented=False), "xi1'an1")
def test_drop_apostrophe(self): self.assertEqual(trans.pinyin_to_zhuyin("xi1'an1"), 'ㄒㄧ ㄢ') self.assertEqual(trans.pinyin_to_ipa("xi1'an1"), 'ɕi˥ an˥') self.assertEqual(trans.to_pinyin("xi1'an1"), "xī'ān") self.assertEqual(trans.pinyin_to_zhuyin("xī'ān"), 'ㄒㄧ ㄢ') self.assertEqual(trans.pinyin_to_ipa("xī'ān"), 'ɕi˥ an˥') self.assertEqual(trans.to_pinyin("xī'ān", accented=False), "xi1'an1")
def test_issue_6(self): pinyin = "zhuójìnr" zhuyin = "ㄓㄨㄛˊ ㄐㄧㄣˋ ㄦ˙" ipa = "ʈʂwɔ˧˥ tɕin˥˩ ɻ" self.assertEqual(zhuyin, trans.pinyin_to_zhuyin(pinyin)) self.assertEqual(ipa, trans.pinyin_to_ipa(pinyin))
def test_issue_6(self): pinyin = 'zhuójìnr' zhuyin = 'ㄓㄨㄛˊ ㄐㄧㄣˋ ㄦ˙' ipa = 'ʈʂwɔ˧˥ tɕin˥˩ ɻ' self.assertEqual(zhuyin, trans.pinyin_to_zhuyin(pinyin)) self.assertEqual(ipa, trans.pinyin_to_ipa(pinyin))
def fetchParsed(self, text, field, note, rType=False): if text == '': return '' if not rType: altType = self.getAltReadingType(note.model()['name'], field) if altType: rType = altType else: rType = self.getReadingType() if rType not in ['pinyin', 'bopomofo', 'jyutping']: return text text = self.removeBrackets(text) finished = False newStr = '' count = 0 while not finished: word = '' if re.search(self.hanziRange, text[count]): word += text[count] lookahead = 10 limit = count + lookahead count += 1 while count < len(text) and count < limit and re.search( self.hanziRange, text[count]): word += text[count] count += 1 result = False while not result and len(word) > 0: if rType == 'jyutping': result = self.db.getJyutping(word) else: result = self.db.getAltFayin(word) if not result: count -= 1 word = word[:-1] if result: if rType == 'jyutping': results = result[0][0].split(" ") else: results = self.manip.separatePinyin( result[0][0]).split(" ") for idx, fayin in enumerate(results): if rType == 'bopomofo': results[idx] = self.bopoToneToNumber( transcriptions.pinyin_to_zhuyin(fayin)) newStr += word + '[' + ' '.join(results).lower() + ']' else: newStr += text[count] count += 1 else: newStr += text[count] count += 1 if count == len(text): finished = True self.addVariants(text, note) self.addSimpTrad(text, note) return newStr
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) zhuyin = pinyin_to_zhuyin(numbered_pinyin) return zhuyin
def test_pinyin_to_zhuyin(self): self.assertEqual(trans.pinyin_to_zhuyin(self.accented_pinyin), self.zhuyin) self.assertEqual(trans.pinyin_to_zhuyin(self.numbered_pinyin), self.zhuyin)
def parse_file(filename, words): with open(filename) as f: data = json.load(f) items_parsed = 0 # Each item in the JSON correspond to one or more entries in the dictionary # Most items map 1:1 to entries, e.g. "物質" is a single entry # Some items are 多音字, so they map to multiple entries (e.g. 重 -> zhòng and chóng) # # In the vocabulary of the the CSLD, each item may correspond to multiple heteronyms, # and each heteronym maps to a single entry. for item in data: # These do not change no matter the heteronym trad = item["title"] simp = HanziConv.toSimplified(trad) jyut = pinyin_jyutping_sentence.jyutping(trad, tone_numbers=True, spaces=True) freq = zipf_frequency(trad, "zh") # Some items have multiple pronunciations (one for Taiwan, one for Mainland China) taiwan_pin = mainland_pin = "" # Build up a list of definitions for each heteronym taiwan_defs = [] mainland_defs = [] # Distinguish between heteronyms by their pinyin – if the pinyin of the # current heteronym does not match the old pinyin, then a new heteronym # must be created last_heteronym_pin = "" last_taiwan_pin = last_mainland_pin = "" # Go through each heteronym, creating Entry objects for each one for heteronym in item["heteronyms"]: if "pinyin" not in heteronym: logging.debug( f'Could not find pinyin for heteronym of word {trad} with definitions {heteronym["definitions"]}' ) continue # Filter out known bad pinyin if (trad in KNOWN_INVALID_SYLLABLES and heteronym["pinyin"] in KNOWN_INVALID_SYLLABLES[trad]): pins = KNOWN_INVALID_SYLLABLES[trad][heteronym["pinyin"]] else: pins = heteronym["pinyin"].split("<br>陸⃝") # Some weird a's cause dragonmapper to break, so replace them with standard a's. pins = list(map(lambda x: x.replace("ɑ", "a"), pins)) # Remove dashes in pinyin pins = list(map(lambda x: x.replace("-", " "), pins)) # Remove commas in pinyin pins = list(map(lambda x: x.replace(",", ""), pins)) # Remove weird characters pins = list(map(lambda x: x.replace("陸⃟", ""), pins)) # Dragonmapper cannot handle some erhua pins = list( map(lambda x: x.replace("diǎr", "diǎn er"), pins)) pins = list( map(lambda x: x.replace("biār", "biān er"), pins)) try: # Converting from pinyin -> zhuyin inserts spaces between characters # Converting from zhuyin -> pinyin conserves these spaces pins = [ transcriptions.zhuyin_to_pinyin( transcriptions.pinyin_to_zhuyin(x), accented=False) for x in pins ] for x in pins: if x.count(" ") >= len(trad): # This means that there was an extra space inserted somewhere; the pinyin is not valid raise ValueError( "Too many spaces in parsed Pinyin!") except Exception as e: # Try parsing zhuyin as a backup pins = heteronym["bopomofo"].split("<br>陸⃝") # Remove weird spaces in zhuyin pins = list(map(lambda x: x.replace(" ", " "), pins)) try: pins = [ transcriptions.zhuyin_to_pinyin(x, accented=False) for x in pins ] except Exception as e: logging.error( f"Unable to split up Pinyin for word {trad}: {e}, skipping word..." ) continue if len(pins) > 1: taiwan_pin = pins[0] mainland_pin = pins[1] else: taiwan_pin = mainland_pin = pins[0] if (last_heteronym_pin != "" and heteronym["pinyin"] != last_heteronym_pin): # A new different pinyin means that we are now processing a new heteronym. # We must create an Entry object for the definitions of the old heteronym # and add it to the list of entries before processing the new one. entry = objects.Entry(trad, simp, last_taiwan_pin, jyut, freq=freq, defs=taiwan_defs) words.append(entry) if last_mainland_pin != last_taiwan_pin: entry = objects.Entry( trad, simp, last_mainland_pin, jyut, freq=freq, defs=mainland_defs, ) words.append(entry) # Reset the definitions list taiwan_defs = [] mainland_defs = [] for definition in heteronym["definitions"]: taiwan_label = "臺" if taiwan_pin != mainland_pin else "" mainland_label = "陸" if mainland_pin != taiwan_pin else "" definition_text = definition["def"] # Take out parts of definitions that should be in labels for pattern in LABEL_REGEX_PATTERNS: if re.match(pattern, definition_text): definition_label, definition_text = re.match( pattern, definition_text).group(1, 2) taiwan_label += ("、" + definition_label if taiwan_label else definition_label) mainland_label += ("、" + definition_label if mainland_label else definition_label) # Remove 臺⃝ and 陸⃝ from definitions, since Qt cannot display them definition_text = definition_text.replace("臺⃝", "臺:") definition_text = definition_text.replace("陸⃝", "陸:") # Insert zero-width spaces so that we can reverse-search the definition taiwan_def_tuple = objects.DefinitionTuple( "".join(jieba.cut(definition_text)), taiwan_label, []) mainland_def_tuple = objects.DefinitionTuple( "".join(jieba.cut(definition_text)), mainland_label, []) # Parse and add examples to this definition if "example" in definition: for example in definition["example"]: if re.match(EXAMPLE_REGEX_PATTERN, example): # Every example is surrounded by "如:<example>", so only keep the example example = re.match(EXAMPLE_REGEX_PATTERN, example).group(1) # Some examples contain multiple examples, so split them up by enclosing brackets 「」 example_texts = re.findall( INDIVIDUAL_EXAMPLE_REGEX_PATTERN, example) else: logging.warning( f"Found example that does not fit the normal example regex pattern: {trad}, {example}" ) # Fall back to splitting on Chinese enumeration comma example_texts = example.split("、") for example_text in example_texts: # Strip out weird whitespace example_text = re.sub(WHITESPACE_REGEX_PATTERN, "", example_text) # Joining and splitting separates series of full-width punctuation marks # into separate items, which is necessary so that lazy_pinyin() returns # separate items for each full-width punctuation mark in the list it returns # # e.g. "《儒林外史.第四六回》:「成老爹道..." turns into # "《 儒 林 外 史 . 第 四 六 回 》 : 「 成 老 爹 道", which turns into # ['《', '儒', '林', '外', '史', '.', '第', '四', '六', '回', '》', ':', '「', '成', '老', '爹', '道'] # (Notice how "》:「"" is now split up into three different items) example_pinyin = lazy_pinyin( " ".join(example_text).split(), style=Style.TONE3, neutral_tone_with_five=True, ) example_pinyin = " ".join( example_pinyin).lower() example_pinyin = example_pinyin.strip( ).replace("v", "u:") # Since the pinyin returned by lazy_pinyin doesn't always match the pinyin # given in the heteronym, attempt to replace pinyin corresponding to the # characters in this heteronym with the pinyin provided by the JSON file. # # e.g. example_text = "重新"; example_pinyin = "zhong4 xin1" (returned by lazy_pinyin) # trad = "重", phrase_pinyin = "chong2" # means that we should convert "zhong4 xin1" to "chong2 xin1" # Strip out variant pronunciations for conversion purposes for index, pin in enumerate( [taiwan_pin, mainland_pin]): phrase_pinyin = pin phrase_pinyin = re.sub( VARIANT_PRONUNCIATION_REGEX_PATTERN, "", phrase_pinyin, ) phrase_pinyin = re.sub( COLLOQUIAL_PRONUNCIATION_REGEX_PATTERN, "", phrase_pinyin, ) # Do not try to match entries formatted like "那搭(Namibia)" if not re.match( STRANGE_ENTRY_REGEX_PATTERN, trad): try: example_pinyin = ( change_pinyin_to_match_phrase( example_text, example_pinyin, trad, phrase_pinyin, )) except Exception as e: logging.warning( f"Couldn't change pinyin in example for word {trad}: " f"{''.join(example_text)}, {example_pinyin}, {pin}, " f"{e}") traceback.print_exc() if index == 0: taiwan_def_tuple.examples.append( objects.ExampleTuple( "zho", example_pinyin, example_text)) elif index == 1: mainland_def_tuple.examples.append( objects.ExampleTuple( "zho", example_pinyin, example_text)) taiwan_defs.append(taiwan_def_tuple) mainland_defs.append(mainland_def_tuple) last_heteronym_pin = heteronym["pinyin"] last_taiwan_pin = taiwan_pin last_mainland_pin = mainland_pin entry = objects.Entry(trad, simp, taiwan_pin, jyut, freq=freq, defs=taiwan_defs) words.append(entry) if mainland_pin != taiwan_pin: entry = objects.Entry(trad, simp, mainland_pin, jyut, freq=freq, defs=mainland_defs) words.append(entry) items_parsed += 1 if not items_parsed % 500: print(f"Parsed entry #{items_parsed}")
def hydrate_word(_word): accented_pinyin = transcriptions.numbered_to_accented( _word.numbered_pinyin) zhuyin = transcriptions.pinyin_to_zhuyin(_word.numbered_pinyin) return ChineseWord(_word.simplified, _word.traditional, accented_pinyin, zhuyin, _word.english)
def finalizeReadings(self, text, field, note, editor=False, rType=False): if text == '': return if note: if not rType: altType = self.getAltReadingType(note.model()['name'], field) if altType: rType = altType else: rType = self.getReadingType() if rType not in ['pinyin', 'bopomofo', 'jyutping']: return text = self.removeBrackets(text) finished = False newStr = '' count = 0 while not finished: word = '' if re.search(self.hanziRange, text[count]): word += text[count] lookahead = 10 limit = count + lookahead count += 1 while count < len(text) and count < limit and re.search( self.hanziRange, text[count]): word += text[count] count += 1 result = False while not result and len(word) > 0: if rType == 'jyutping': result = self.db.getJyutping(word) else: result = self.db.getAltFayin(word) if not result: count -= 1 word = word[:-1] if result: if rType == 'jyutping': results = result[0][0].split(" ") else: results = self.manip.separatePinyin( result[0][0]).split(" ") for idx, fayin in enumerate(results): if rType == 'bopomofo': results[idx] = self.bopoToneToNumber( transcriptions.pinyin_to_zhuyin(fayin)) newStr += word + '[' + ' '.join(results).lower() + ']' else: newStr += text[count] count += 1 ###importantcheck if word not found look for char pinyin or jyutping else: newStr += text[count] count += 1 if count == len(text): finished = True if editor: editor.web.eval(self.commonJS + self.insertHTMLJS % newStr.replace('"', '\\"')) # note[field] = newStr self.addVariants(text, note, editor) self.addSimpTrad(text, note, editor) else: return newStr