質問

単語内の音節を検出するかなり効率的な方法を見つける必要があります。例:

非表示-> in-vi-sib-le

使用できる音節規則がいくつかあります:

V 履歴書 VC CVC CCV CCCV CVCC

* Vは母音、Cは子音です。 例:

発音(5代名詞; CV-CVC-CV-V-CVC)

私はいくつかの方法を試しましたが、そのうち、正規表現(音節を数えたい場合にのみ役立ちます)またはハードコーディングされたルール定義(非常に非効率であることが判明するブルートフォースアプローチ)を使用し、最終的に有限状態オートマトンを使用しました(これは有用な結果にはなりませんでした)。

このアプリケーションの目的は、特定の言語ですべての音節の辞書を作成することです。この辞書は、後でスペルチェックアプリケーション(ベイジアン分類子を使用)および音声合成のテキストに使用されます。

以前のアプローチに加えて、この問題を解決する別の方法に関するヒントをいただければ幸いです。

私はJavaで働いていますが、C / C ++、C#、Python、Perlのあらゆるヒントは私にとってはうまくいくでしょう。

役に立ちましたか?

解決

ハイフネーションを目的としたこの問題に対するTeXのアプローチについて読んでください。特に、Frank Liangの論文の論文を参照してください。 Comによる単語のハイフンput-er 。彼のアルゴリズムは非常に正確で、アルゴリズムが機能しない場合のための小さな例外辞書が含まれています。

他のヒント

私はこのページを偶然見つけて同じものを探し、ここでLiang論文の実装をいくつか見つけました。 https://github.com/mnater/hyphenator

これは、自由に利用可能なコードを非固有の問題に適応させる代わりに、60ページの論文を読むのが好きなタイプでない限りです。 :)

NLTK を使用したソリューションです:

from nltk.corpus import cmudict
d = cmudict.dict()
def nsyl(word):
  return [len(list(y for y in x if y[-1].isdigit())) for x in d[word.lower()]] 

テキストブロックのflesch-kincaidとfleschの読み取りスコアを計算するプログラムでこの問題に取り組んでいます。私のアルゴリズムは、このウェブサイトで見つけたものを使用します: http://www.howmanysyllables.com/howtocountsyllables.htmlそしてそれは適度に近くなります。目に見えない、ハイフネーションなどの複雑な単語にはまだ問題がありますが、私の目的のために球場に入ることがわかりました。

実装が簡単であるという利点があります。 「es」が見つかりました。音節文字である場合とそうでない場合があります。ギャンブルですが、アルゴリズムのesを削除することにしました。

private int CountSyllables(string word)
    {
        char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y' };
        string currentWord = word;
        int numVowels = 0;
        bool lastWasVowel = false;
        foreach (char wc in currentWord)
        {
            bool foundVowel = false;
            foreach (char v in vowels)
            {
                //don't count diphthongs
                if (v == wc && lastWasVowel)
                {
                    foundVowel = true;
                    lastWasVowel = true;
                    break;
                }
                else if (v == wc && !lastWasVowel)
                {
                    numVowels++;
                    foundVowel = true;
                    lastWasVowel = true;
                    break;
                }
            }

            //if full cycle and no vowel found, set lastWasVowel to false;
            if (!foundVowel)
                lastWasVowel = false;
        }
        //remove es, it's _usually? silent
        if (currentWord.Length > 2 && 
            currentWord.Substring(currentWord.Length - 2) == "es")
            numVowels--;
        // remove silent e
        else if (currentWord.Length > 1 &&
            currentWord.Substring(currentWord.Length - 1) == "e")
            numVowels--;

        return numVowels;
    }

これは特に難しい問題であり、LaTeXハイフネーションアルゴリズムでは完全には解決されません。使用可能ないくつかの方法と関連する課題の概要は、論文にあります。英語の自動音節化アルゴリズムの評価(Marchand、Adsett、およびDamper 2007)。

C#での迅速で汚い実装を共有してくれたJoe Basiricoに感謝します。私は大きなライブラリを使用しましたが、それらは機能しますが、通常は少し遅く、プロジェクトを迅速に行うには、メソッドが正常に機能します。

Javaのコードとテストケースを次に示します。

public static int countSyllables(String word)
{
    char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y' };
    char[] currentWord = word.toCharArray();
    int numVowels = 0;
    boolean lastWasVowel = false;
    for (char wc : currentWord) {
        boolean foundVowel = false;
        for (char v : vowels)
        {
            //don't count diphthongs
            if ((v == wc) && lastWasVowel)
            {
                foundVowel = true;
                lastWasVowel = true;
                break;
            }
            else if (v == wc && !lastWasVowel)
            {
                numVowels++;
                foundVowel = true;
                lastWasVowel = true;
                break;
            }
        }
        // If full cycle and no vowel found, set lastWasVowel to false;
        if (!foundVowel)
            lastWasVowel = false;
    }
    // Remove es, it's _usually? silent
    if (word.length() > 2 && 
            word.substring(word.length() - 2) == "es")
        numVowels--;
    // remove silent e
    else if (word.length() > 1 &&
            word.substring(word.length() - 1) == "e")
        numVowels--;
    return numVowels;
}

public static void main(String[] args) {
    String txt = "what";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
    txt = "super";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
    txt = "Maryland";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
    txt = "American";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
    txt = "disenfranchized";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
    txt = "Sophia";
    System.out.println("txt="+txt+" countSyllables="+countSyllables(txt));
}

結果は予想どおりでした(Flesch-Kincaidには十分に機能します):

txt=what countSyllables=1
txt=super countSyllables=2
txt=Maryland countSyllables=3
txt=American countSyllables=3
txt=disenfranchized countSyllables=5
txt=Sophia countSyllables=2

@Tihamerと@ joe-basiricoをバンプします。非常に便利な機能で、完璧ではありませんが、ほとんどの中小規模のプロジェクトに適しています。ジョー、私はあなたのコードの実装をPythonで書き直しました:

def countSyllables(word):
    vowels = "aeiouy"
    numVowels = 0
    lastWasVowel = False
    for wc in word:
        foundVowel = False
        for v in vowels:
            if v == wc:
                if not lastWasVowel: numVowels+=1   #don't count diphthongs
                foundVowel = lastWasVowel = True
                        break
        if not foundVowel:  #If full cycle and no vowel found, set lastWasVowel to false
            lastWasVowel = False
    if len(word) > 2 and word[-2:] == "es": #Remove es - it's "usually" silent (?)
        numVowels-=1
    elif len(word) > 1 and word[-1:] == "e":    #remove silent e
        numVowels-=1
    return numVowels

誰かがこれが便利だと思ってください!

Perlには Lingua :: Phonology :: Syllable モジュール。それを試すか、そのアルゴリズムを調べてみてください。私はそこにいくつかの他の古いモジュールも見ました。

正規表現が音節の数だけを与える理由がわかりません。キャプチャ括弧を使用して音節自体を取得できるはずです。正常に機能する正規表現を作成できると仮定します。つまり、

今日 this Frank Liangの英語またはドイツ語のパターンを持つハイフネーションアルゴリズムのJava実装が見つかりました。 Maven Centralで利用できます。

洞窟: .tex パターンファイルの最後の行を削除することが重要です。そうしないと、それらのファイルはMaven Centralの現在のバージョンでロードできません。

hyphenator をロードして使用するには、次のJavaコードスニペットを使用できます。 texTable は、必要なパターンを含む .tex ファイルの名前です。これらのファイルは、プロジェクトのgithubサイトで入手できます。

 private Hyphenator createHyphenator(String texTable) {
        Hyphenator hyphenator = new Hyphenator();
        hyphenator.setErrorHandler(new ErrorHandler() {
            public void debug(String guard, String s) {
                logger.debug("{},{}", guard, s);
            }

            public void info(String s) {
                logger.info(s);
            }

            public void warning(String s) {
                logger.warn("WARNING: " + s);
            }

            public void error(String s) {
                logger.error("ERROR: " + s);
            }

            public void exception(String s, Exception e) {
                logger.error("EXCEPTION: " + s, e);
            }

            public boolean isDebugged(String guard) {
                return false;
            }
        });

        BufferedReader table = null;

        try {
            table = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream((texTable)), Charset.forName("UTF-8")));
            hyphenator.loadTable(table);
        } catch (Utf8TexParser.TexParserException e) {
            logger.error("error loading hyphenation table: {}", e.getLocalizedMessage(), e);
            throw new RuntimeException("Failed to load hyphenation table", e);
        } finally {
            if (table != null) {
                try {
                    table.close();
                } catch (IOException e) {
                    logger.error("Closing hyphenation table failed", e);
                }
            }
        }

        return hyphenator;
    }

その後、 Hyphenator を使用する準備ができました。音節を検出するための基本的な考え方は、指定されたハイフンで用語を分割することです。

    String hyphenedTerm = hyphenator.hyphenate(term);

    String hyphens[] = hyphenedTerm.split("\u00AD");

    int syllables = hyphens.length;

APIは通常の"-" を返さないため、" \ u00AD "で分割する必要があります。

このアプローチは、多くの異なる言語をサポートし、ドイツ語のハイフネーションをより正確に検出するため、Joe Basiricoの答えよりも優れています。

なぜ計算するのですか?すべてのオンライン辞書にはこの情報があります。 http://dictionary.reference.com/browse/invisible in· vis· i· ble

@ joe-basiricoと@tihamerに感謝します。 @tihamerのコードをLua 5.1、5.2、およびluajit 2に移植しました(ほとんどの場合、luaの他のバージョンでも実行されます):

countsyllables.lua

function CountSyllables(word)
  local vowels = { 'a','e','i','o','u','y' }
  local numVowels = 0
  local lastWasVowel = false

  for i = 1, #word do
    local wc = string.sub(word,i,i)
    local foundVowel = false;
    for _,v in pairs(vowels) do
      if (v == string.lower(wc) and lastWasVowel) then
        foundVowel = true
        lastWasVowel = true
      elseif (v == string.lower(wc) and not lastWasVowel) then
        numVowels = numVowels + 1
        foundVowel = true
        lastWasVowel = true
      end
    end

    if not foundVowel then
      lastWasVowel = false
    end
  end

  if string.len(word) > 2 and
    string.sub(word,string.len(word) - 1) == "es" then
    numVowels = numVowels - 1
  elseif string.len(word) > 1 and
    string.sub(word,string.len(word)) == "e" then
    numVowels = numVowels - 1
  end

  return numVowels
end

そして、それが機能することを確認するためのいくつかの楽しいテスト(想定どおりに):

countsyllables.tests.lua

require "countsyllables"

tests = {
  { word = "what", syll = 1 },
  { word = "super", syll = 2 },
  { word = "Maryland", syll = 3},
  { word = "American", syll = 4},
  { word = "disenfranchized", syll = 5},
  { word = "Sophia", syll = 2},
  { word = "End", syll = 1},
  { word = "I", syll = 1},
  { word = "release", syll = 2},
  { word = "same", syll = 1},
}

for _,test in pairs(tests) do
  local resultSyll = CountSyllables(test.word)
  assert(resultSyll == test.syll,
    "Word: "..test.word.."\n"..
    "Expected: "..test.syll.."\n"..
    "Result: "..resultSyll)
end

print("Tests passed.")

音節を数える適切な方法が見つからなかったため、自分でメソッドを設計しました。

ここで私のメソッドを見ることができます: https://stackoverflow.com/a/32784041/2734752

辞書とアルゴリズムの方法を組み合わせて、音節を数えます。

ここで私のライブラリを表示できます: https://github.com/troywatson/Lawrence-スタイルチェッカー

アルゴリズムをテストしたところ、攻撃率は99.4%でした!

Lawrence lawrence = new Lawrence();

System.out.println(lawrence.getSyllable("hyphenation"));
System.out.println(lawrence.getSyllable("computer"));

出力:

4
3

少し前に、まったく同じ問題に遭遇しました。

すぐに CMU発音辞書を使用して、ほとんどの単語の正確な検索。辞書にない単語については、音節カウントの予測で最大98%正確な機械学習モデルに戻りました。

ここでは、使いやすいpythonモジュールですべてをまとめました: https:// github.com/repp/big-phoney

インストール: pip install big-phoney

音節のカウント:

from big_phoney import BigPhoney
phoney = BigPhoney()
phoney.count_syllables('triceratops')  # --> 4

Pythonを使用しておらず、MLモデルベースのアプローチを試してみたい場合は、かなり詳細な Kaggleでの音節カウントモデルの動作について説明します

多くのテストを行い、ハイフネーションパッケージも試した後、いくつかの例に基づいて自分で書いた。ハイフネーション辞書と連動する pyhyphen および pyphen パッケージも試しましたが、多くの場合、間違った数の音節が生成されます。 nltk パッケージは、このユースケースには遅すぎます。

Pythonでの私の実装は、私が書いたクラスの一部であり、音節のカウントルーチンを以下に貼り付けます。静かな単語の終わりを説明する良い方法をまだ見つけていないので、音節の数を少し過大評価します。

この関数は、Flesch-Kincaid可読性スコアに使用されるため、単語ごとの音節の比率を返します。数値は正確である必要はなく、推定に十分近い値です。

私の第7世代i7 CPUでは、この関数は759ワードのサンプルテキストに対して1.1〜1.2ミリ秒かかりました。

def _countSyllablesEN(self, theText):

    cleanText = ""
    for ch in theText:
        if ch in "abcdefghijklmnopqrstuvwxyz'’":
            cleanText += ch
        else:
            cleanText += " "

    asVow    = "aeiouy'’"
    dExep    = ("ei","ie","ua","ia","eo")
    theWords = cleanText.lower().split()
    allSylls = 0
    for inWord in theWords:
        nChar  = len(inWord)
        nSyll  = 0
        wasVow = False
        wasY   = False
        if nChar == 0:
            continue
        if inWord[0] in asVow:
            nSyll += 1
            wasVow = True
            wasY   = inWord[0] == "y"
        for c in range(1,nChar):
            isVow  = False
            if inWord[c] in asVow:
                nSyll += 1
                isVow = True
            if isVow and wasVow:
                nSyll -= 1
            if isVow and wasY:
                nSyll -= 1
            if inWord[c:c+2] in dExep:
                nSyll += 1
            wasVow = isVow
            wasY   = inWord[c] == "y"
        if inWord.endswith(("e")):
            nSyll -= 1
        if inWord.endswith(("le","ea","io")):
            nSyll += 1
        if nSyll < 1:
            nSyll = 1
        # print("%-15s: %d" % (inWord,nSyll))
        allSylls += nSyll

    return allSylls/len(theWords)

jsoupを使用してこれを1回行いました。次に音節パーサーのサンプルを示します。

public String[] syllables(String text){
        String url = "https://www.merriam-webster.com/dictionary/" + text;
        String relHref;
        try{
            Document doc = Jsoup.connect(url).get();
            Element link = doc.getElementsByClass("word-syllables").first();
            if(link == null){return new String[]{text};}
            relHref = link.html(); 
        }catch(IOException e){
            relHref = text;
        }
        String[] syl = relHref.split("·");
        return syl;
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top