簡體   English   中英

如何使用變量和標記實現馬爾可夫算法?

[英]How can I implement Markov's algorithm with variables and markers?

我一直在嘗試實現馬爾可夫算法,但僅獲得了部分成功。 該算法非常簡單,可以在此處找到。

但是,我的項目有一個額外的困難,我必須使用包含標記和變量的規則。

變量代表字母中的任何字母,標記只是一個字符,用作將變量四處移動的參考(它沒有實數值)。

此示例復制字符串中的每個字符:

字母:{a,b,c}

標記:{M}

變量:{x}

規則1:Mx-> xxM

規則2:xM-> x

規則3:x-> Mx

輸入:abc

abc //我們應用規則3

Mabc //我們應用規則1

aaMbc //我們應用規則1

aabbMc //我們應用規則1

aabbccM //我們應用規則2

為aabbcc

這是我的遞歸函數,實現了markov算法,該算法僅適用於字符串輸入,例如:規則1:“蘋果”->“橙色”,輸入:“蘋果”。

public static String markov(String input, LinkedList<Rule> rules) {
    for (Rule rule : rules) {
        if (!input.equals(input.replace(rule.getFrom(), rule.getTo()))) { //If the rule matches a substring
            if (rule.isTerminating()) { //If the rule is terminating
                input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
                System.out.println(input); //Replace the first instance
                return input; //return and end the cycle
            } else {
                input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
                System.out.println(input);
                return markov(input, rules); //Start looking again for matching rules
            }
        }
    }
    return input;
}

我不知道如何在此邏輯中實現變量和標記,以便有人可以教育我實現該邏輯的最佳方法? 任何建議都歡迎。

如果問題不符合SO准則,請在評論中告訴我原因,以免重復錯誤。

謝謝!

GitHub上

我認為最簡單的方法是使用Java正則表達式。 一旦解決了這些問題,下面的規則將適用於您的示例:

Rule 1: "M([a-c])" -> "$1$1M"
Rule 2: "([a-c])M" -> "$1" (terminating)
Rule 3: "([a-c])"  -> "M$1"

請注意,您需要對當前方法進行一些調整才能使其正常工作。

replace將文字字符串作為第一個參數,而replaceFirst使用正則表達式,因此:

replace: if (!input.equals(input.replace(rule.getFrom(), rule.getTo()))) {
with:    if (!input.equals(input.replaceFirst(rule.getFrom(), rule.getTo()))) {

您引用的是rule.getFrom()字符串,該字符串不適用於正則表達式,因此:

replace: input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
with:    input = input.replaceFirst(rule.getFrom(), rule.getTo());

到那時,您在兩次調用replaceFirst的代碼中有一些重復,因此您可以將它第一次粘貼在temp變量中replaceFirst用它:

String next = input.replace(rule.getFrom(), rule.getTo());
if (!input.equals(next)) {
  ...
  input = next;
  ...
}

當您當前引用整個rule.getFrom()字符串時,我想您以前在使用正則表達式特殊字符時遇到了問題。 如果是這樣,則在創建規則時需要分別解決它們。 我真的不想在這里進入正則表達式,因為它是一個很大的領域,並且與Markov算法完全分開,所以如果您對此有疑問,請在線進行一些研究(例如, 正則表達式捕獲組 ),或在此處針對正則表達式特定的問題提出一個單獨的問題。

請注意,您仍然可以將這些規則與常規規則結合使用(將標記字符從M更改為#以允許在字母表中使用M ),請遵循以下規則:

"A"             -> "apple"
"B"             -> "bag"
"S"             -> "shop"
"T"             -> "the"
"the shop"      -> "my brother"
"#([a-zA-Z .])" -> "$1$1#"
"([a-zA-Z .])#" -> "$1" (terminating)
"([a-zA-Z .])"  -> "#$1"

將轉換為:

from: I bought a B of As from T S.
to:   II  bboouugghhtt  aa  bbaagg  ooff  aapppplleess  ffrroomm  mmyy  bbrrootthheerr..

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM