単語が書かれたファイルに発音記号を追加する

課題
ディレクトリ'tango'にある単語のファイル(words_list.txt)にアメリカ英語の発音記号(IPA)を追加してphonetic_list.txtとして書き出すpythonコード 

windows10
PS> python words_phonetic_symbols.py

pip install eng-to-ipa
を実行してライブラリをインストールする。

・ファイル構造:
tango/
  words_list.txt
  phonetic_list.txt

・words_list.txt:入力ファイル例
1,man
2,people
3,life
4,child
5,person

・phonetic_list.txt:出力ファイル例
1,man,mæn
2,people,ˈpipəl
3,life,laɪf
4,child,ʧaɪld
5,person,ˈpərsən

■python コード例

import eng_to_ipa as ipa
import os

def get_ipa(word):
    return ipa.convert(word, retrieve_all=False)

def add_ipa_to_words(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
        for line in infile:
            parts = line.strip().split(',')
            if len(parts) == 2:
                index, word = parts
                ipa_transcription = get_ipa(word.lower())
                outfile.write(f"{index},{word},{ipa_transcription}\n")

directory = "tango"
words_file = os.path.join(directory, "words_list.txt")
phonetic_file = os.path.join(directory, "phonetic_list.txt")

add_ipa_to_words(words_file, phonetic_file)
print("IPA追加完了: phonetic_list.txt に出力しました。")