# -*- coding: utf-8 -*- """ This script converts a string of Chinese characters (Hanzi) into Pinyin with tone marks. Usage: python get_pinyin.py "你的汉字" Example: python get_pinyin.py "你好" Expected output: nǐ hǎo """ import sys from pypinyin import pinyin, Style def get_pinyin(text): """ Converts a string of Hanzi characters to a Pinyin string with tone marks. Args: text (str): The Hanzi string to convert. Returns: str: The resulting Pinyin string. """ # The pinyin() function returns a list of lists, e.g., [['nǐ'], ['hǎo']] # We use a list comprehension to flatten it and then join the elements with a space. pinyin_list = pinyin(text, style=Style.TONE) return " ".join([item[0] for item in pinyin_list]) if __name__ == "__main__": # Check if a command-line argument was provided if len(sys.argv) > 1: # The first argument (sys.argv[0]) is the script name, # so the Hanzi text is the second argument (sys.argv[1]). hanzi_text = sys.argv[1] pinyin_output = get_pinyin(hanzi_text) print(pinyin_output) else: # If no argument is provided, print the usage instructions. print('Usage: python get_pinyin.py "你的汉字"') print('Example: python get_pinyin.py "你好"')