The GetPhonetic member of the Excel Application object is a method that retrieves the Japanese phonetic (furigana) text for a specified string or cell. This is particularly useful when working with Japanese data, as it allows you to programmatically access the phonetic guides often used to indicate the pronunciation of Kanji characters. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model.
The syntax for calling GetPhonetic in xlwings is as follows:
app.api.GetPhonetic(Text)
Where:
appis an instance of the xlwingsAppclass, representing the Excel application.Text(optional): This parameter specifies the text for which to retrieve the phonetic information. It can be a string or a reference to a cell. If omitted, the method returns the phonetic text for the last processed text.
The Text parameter accepts different types of inputs, which determine its behavior:
| Input Type | Description |
|---|---|
| String | A literal text string (e.g., "東京"). The method returns the phonetic text for that string. |
| Range Reference | A reference to a cell (e.g., app.range('A1')). The method returns the phonetic text for the cell’s value. |
| Omitted | If the parameter is not provided, Excel uses the last text that was processed for phonetics. |
It’s important to note that the GetPhonetic method is primarily designed for Japanese text and may not return meaningful results for other languages. Additionally, the phonetic information must be present in the Excel file; it is often added through features like “Phonetic Guide” in Excel’s UI.
Here are two xlwings code examples demonstrating the use of GetPhonetic:
Example 1: Retrieving phonetic text from a string
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Get phonetic text for the Japanese string "東京" (Tokyo)
phonetic_text = app.api.GetPhonetic("東京")
print(phonetic_text) # Output might be "トウキョウ" depending on Excel's settings
Example 2: Retrieving phonetic text from a cell
import xlwings as xw
# Start a new workbook
wb = xw.Book()
sheet = wb.sheets[0]
# Write a Japanese word with phonetic guide to cell A1 (assume phonetic is added via Excel)
sheet.range('A1').value = "東京"
# Retrieve the phonetic text from cell A1
phonetic_text = wb.app.api.GetPhonetic(sheet.range('A1'))
print(phonetic_text) # Output will be the phonetic text associated with the cell's content
Leave a Reply