Javascript面向对象的海盗翻译

时间:2014-06-01 02:03:03

标签: javascript

我需要在javascript中为我的最终制作一个面向对象的盗版翻译器,我有一个想法并且有一些代码但是无法在我的页面上正确输出它。我设置了它,所以你在一个框中键入英语短语,然后在另一个框中它吐出海盗版本。我不会单步执行我的对象数组。我会发布代码。感谢您提供的任何帮助!!!

 var $ = function(id) { return document.getElementById(id); }


var Dictionary = [{
    Greetings: {
        hello:"ahoy",
        hi:"yohoho",
        pardon_me:"avast",
        excuse_me:"arrr"
    },
    People: {
        stranger:"scurvy",
        sir:"matey",
        madam:"proud beauty",
        miss:"comely wench",
        officer:"foul blaggart",
        enemy:"scallywag"
    },
    Questions: {
        where_is:"whar be",
        can_you_help_me_find:"know ye",
        is_that:"be that",
        how_far_is_it_to:"how many leagues to"
    },
    Articles: {
        the:"th",
        a:"a briny",
        any:"some godforsaken",
        nearby:"broadside",
        my:"me",
        your:"yer"
    },
    Adjectives: {
        old:"barnacle-covered",
        attractive:"comely",
        happy:"grog-filled"
    },
    Places: {
        restroom:"head",
        restaurant:"galley",
        hotel:"fleabag inn",
        mall:"market",
        pub:"Skull & Scuppers",
        bank:"buried trasure"
    },
    Desires: {
        I_would_like_to:"I be needin to",
        I_desire:"I have a fierce fire in me belly",
        I_wish_I_knew_how_to:"I be hankerin to",
        my_mother_told_me_to:"me dear ol mum, bless her black soul, tol me to",
        my_companion_would_like_to:"me mate, ol Rumpot, wants to"
    },
    Actions: {
        find:"come across",
        take_a_nap:"have a bit of a lie down",
        make_a_withdrawal:"seize all yer doubloons",
        have_a_cocktail:"swill a pint or two of grog",
        kill_him:"blow the man down",
        frown:"hang the jib",
        take_a_hike:"walk the plank"
    },

}];

function Translate(text)
    // Returns: a copy of text with English phrases replaced by piratey equivalents 
    {
        for (var i = 0; i < Dictionary.length; i++) {
            var toReplace = new RegExp("\\b"+Dictionary[i][0]+"\\b", "i");

            var index = text.search(toReplace);
            while (index != -1) {
               text = text.replace(toReplace, Dictionary[x][y]);
               index = text.search(toReplace);
            }
        }

        text = text.replace(/\./g, function() {
            return Math.random() < 0.5 ? ". arrrrrrrrr" : "."
        });
        return text.charAt(0).toUpperCase() + text.substring(1);
    }

    var clear_click = function() {
    $("output1").value = "";
    $("output2").value = "";
}

window.onload = function() {
    $("clear").onclick = clear_click;
}



/*for (var x in Dictionary) {
    for (var y in Dictionary[x])
        console.log (y, Dictionary[x][y]);
}*/

HTML:

    <!doctype html>
    <html>

    <head>
      <meta charset="utf-8">
      <title> Pirate Translator </title>
      <script src="js/test2.js"></script>
      <link rel="stylesheet" href="css/normalize.css"/>
      <link rel="stylesheet" href="css/styles.css"/>
    </head>

    <body>
        <h1>Jacob's Pirate Translator</h1>
        <p>Simply click on the buttons to translate<br />
           words and/or phrases from English to pirate talk.
        <hr />
    <form name="TalkForm">

        <table>
        <tr><td align="center"><b>English</b>
            <td>
            <td align="center"><b>Pirate</b>
        <tr><td><textarea name="English" id="output1" rows=12 cols=35 wrap="virtual"></textarea> </td>
            <td align="center"> <br />
                <input type="button" value="Translate --->" 
                       onclick="document.TalkForm.Pirate.value =
                                  Translate(document.TalkForm.English.value);"> </td>
            <td><textarea name="Pirate" id="output2" rows=12 cols=35 wrap="virtual"></textarea> </td>
            <input type="button" id="clear" value="clear">
        </tr>
        </table>
      </form>
      </body>
    </html>

1 个答案:

答案 0 :(得分:1)

EDIT2:我修改了你的词典。如果您遵循我的词典格式,您可以根据需要深入了解数组。它应该工作。我已经在所有不同类型的订单中测试了您的示例,并且在字典中找不到文本。随意尝试一下。

为了增加挑战,我制作了递归函数。 :D不用于/ while循环。

DEMO

var Dictionary = {
    hello: "ahoy",
    hi: "yohoho",
    pardon: [1, {
        me: "avast"
    }],
    excuse: [1, {
        me: "arrr"
    }],
    stranger: "scurvy",
    sir: "matey",
    madam: "proud beauty",
    miss: "comely wench",
    officer: "foul blaggart",
    enemy: "scallywag",
    where: [1, {
        is: "whar be"
    }],
    can: [4, {
        you_help_me_find: "know ye"
    }],
    is: [1, {
        that: "be that"
    }],
    how: [4, {
        far_is_it_to: "how many leagues to"
    }],
    the: "th",
    a: "a briny",
    any: "some godforsaken",
    nearby: "broadside",
    my: "me",
    your: "yer",
    old: "barnacle-covered",
    attractive: "comely",
    happy: "grog-filled",
    restroom: "head",
    restaurant: "galley",
    hotel: "fleabag inn",
    mall: "market",
    pub: "Skull & Scuppers",
    bank: "buried trasure",
    would: [1, {
        like: "be needin"
    }],
    I: [
        [1, {
            desire: "I have a fierce fire in me belly"
        }],
        [5, {
            wish_I_knew_how_to: "I be hankerin to"
        }]
    ],
    my: [
        [4, {
            mother_told_me_to: "me dear ol mum, bless her black soul, tol me to"
        }],
        [4, {
            companion_would_like_to: "me mate, ol Rumpot, wants to"
        }]
    ],
    find: "come across",
    take: [2, {
        a_nap: "have a bit of a lie down"
    }],
    make: [2, {
        a_withdrawal: "seize all yer doubloons"
    }],
    have: [2, {
        a_cocktail: "swill a pint or two of grog"
    }],
    kill: [1, {
        him: "blow the man down"
    }],
    frown: "hang the jib",
    take: [2, {
        a_hike: "walk the plank"
    }]

};

function translate(text) {
    var hop = 1;
    var textToReturn = "";
    //checking if the text is already split, if not we split
    if (typeof text === 'string') {
        text = text.split(' ');
    }
    if (text.length > 0) {
        if (typeof Dictionary[text[0]] == 'undefined' || typeof Dictionary[text[0]] === 'string') {
            textToReturn = (Dictionary[text[0]] || text[0]);
            text = text.slice(hop, text.length);
        } else {
           var info = recursiveCheck(text, Dictionary[text[0]]);
            textToReturn =  (info.hop == 1) ? text[0] : info.text;
            text = text.splice(info.hop, text.length);
        }
        if(text.length > 0)
        {
             textToReturn += ' ' + translate(text);  
        }

    }
    return textToReturn;
}
function recursiveCheck(text, arr)
{
    var found = {hop:1, text: ''};
    if(arr.length > 0)
    {
        if(typeof parseInt(arr[0]) === 'number' && text.length-1 >= arr[0])
        {
            var phrase = text.slice(1, arr[0]+1);
            if(arr[1][phrase.join('_')])
            {
                 found.hop = arr[0]+1;
                 found.text = arr[1][phrase.join('_')];
            }
        }
        else
        {
             found = recursiveCheck(text, arr[0] || []);  
             if(found.hop == 1 && arr.length > 1)
             {
                  found = recursiveCheck(text, arr.slice(1, arr.length));
             }
        }
    }
    return found;
}
var tra = document.getElementById('translate');
var pir = document.getElementById('pirate');
pir.disabled = true;
var eng = document.getElementById('english');

eng.onkeyup = function(){
     pir.value = "";   
}
tra.onclick = function () {
    pir.value = translate(eng.value);
};

如果你想进一步使用字典,HERE就是一个深度数组的例子:

...
        I: [
            [1, {
                desire: [
                          [1,{ a: "I have a fierce fire in me belly"}],
                          [1,{ one: "I have one fierce fire in me belly"}]

            }],
            [5, {
                wish_I_knew_how_to: "I be hankerin to"
            }]
        ],
...

当然我还没有尝试过,但是如果你确实需要它可以工作的话。祝你好运。

编辑:此代码的重点是显示如何访问您的列表。您似乎没有在代码中使用类别,为什么要使用它们?

对于简单的翻译,您的列表看起来有点复杂。最后我查了一下,字典没有类别。开玩笑说我已经简化了你的清单。

var Dictionary = {
        hello:"ahoy",
        hi:"yohoho",
        pardon_me:"avast",
        excuse_me:"arrr",
        stranger:"scurvy",
        sir:"matey",
        madam:"proud beauty",
        miss:"comely wench",
        officer:"foul blaggart",
        enemy:"scallywag",
        where_is:"whar be",
        can_you_help_me_find:"know ye",
        is_that:"be that",
        how_far_is_it_to:"how many leagues to",
        the:"th",
        a:"a briny",
        any:"some godforsaken",
        nearby:"broadside",
        my:"me",
        your:"yer",
        old:"barnacle-covered",
        attractive:"comely",
        happy:"grog-filled",
        restroom:"head",
        restaurant:"galley",
        hotel:"fleabag inn",
        mall:"market",
        pub:"Skull & Scuppers",
        bank:"buried trasure",
        I_would_like_to:"I be needin to",
        I_desire:"I have a fierce fire in me belly",
        I_wish_I_knew_how_to:"I be hankerin to",
        my_mother_told_me_to:"me dear ol mum, bless her black soul, tol me to",
        my_companion_would_like_to:"me mate, ol Rumpot, wants to",
        find:"come across",
        take_a_nap:"have a bit of a lie down",
        make_a_withdrawal:"seize all yer doubloons",
        have_a_cocktail:"swill a pint or two of grog",
        kill_him:"blow the man down",
        frown:"hang the jib",
        take_a_hike:"walk the plank"

};

function translate(text)
{
    pir.value = Dictionary[text.split(' ').join('_')] || 'not found';

}

var tra = document.getElementById('translate');
var pir = document.getElementById('pirate');
pir.disabled = true;
var eng = document.getElementById('english');

tra.onclick = function(){ translate(eng.value) };

HTML:

<input id="english" type="text" placeholder="english"/>
<input id="pirate" placeholder="pirate"/>
<button id="translate">Translate</button>

我已经简化了代码(很多),所以我可以得到一个简单的工作模型。

工作jsfiddle:http://jsfiddle.net/Grimbode/f296h/2/