| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- # encoding: utf8
- import inflect
- # 创建inflect引擎实例
- p = inflect.engine()
- # 自定义单复数词表
- p.defnoun("appendix", "appendices")
- p.defnoun("bus", "buses")
- p.defnoun("thesis", "theses")
- p.defnoun("index", "indices")
- p.defnoun("axis", "axes")
- p.defnoun("cactus", "cacti")
- p.defnoun("focus", "foci")
- p.defnoun("fungus", "fungi")
- p.defnoun("radius", "radii")
- p.defnoun("nucleus", "nuclei")
- p.defnoun("synopsis", "synopses")
- p.defnoun("crisis", "crises")
- p.defnoun("analysis", "analyses")
- p.defnoun("diagnosis", "diagnoses")
- p.defnoun("phenomenon", "phenomena")
- p.defnoun("criterion", "criteria")
- p.defnoun("matrix", "matrices")
- p.defnoun("die", "dies")
- # 用户自定义的单数单词词表
- USER_DEFINED_SINGULAR_WORDS = [singular_word.lower() for singular_word in p.pl_sb_user_defined[::2]]
- def singular(word: str):
- """
- 将复数名词转换为单数形式。
- :param word: 需要转换的名词, eg:"COMPONENTS"
- :return: 单数形式的名词, "COMPONENT"
- """
- if word is None or word.strip() == '':
- return word
- try:
- word_l = word.lower()
- # 用户自定义的单数单词列表
- if word_l in USER_DEFINED_SINGULAR_WORDS:
- return word
- # ss结尾, 's结尾
- if word_l.endswith("ss") or word_l.endswith("'s"):
- return word
- # 单词长度小于3
- if len(word) <= 3 and word_l not in ["men"]:
- return word
- singular_form = p.singular_noun(word)
- if singular_form is False:
- # 如果word本身就是单数形式,则直接返回原字符串
- return word
- return singular_form
- except Exception as _:
- return word
- def phrase_singular(phrase: str):
- """
- 将词组的最后一个单词复数转单数
- :param phrase: eg:"GEARBOX COMPONENTS"
- :return: "GEARBOX COMPONENT"
- """
- if phrase is None or phrase == '':
- return None
- words = phrase.split()
- if len(words) > 1:
- tmp = words[0: -1]
- tmp.append(singular(words[-1]))
- return " ".join(tmp)
- else:
- return singular(phrase)
|