フレーズの頭字語


12

仕事:

たとえばdftba、頭字語を入力として使用するプログラムを作成し、頭字語が表す可能性のあるフレーズを生成します。wordlistを単語入力として使用できます。https://www.youtube.com/watch?v=oPUxnpIWt6Eに触発された

例:

input: dftba
output: don't forget to be awesome

ルール:

  • プログラムは同じ頭字語に対して毎回同じフレーズを生成することはできません。ランダム化が必要です
  • 入力はすべて小文字になります
  • いくつかの例を投稿する(入力と出力)
  • すべての言語が受け入れられます
  • それはので、ほとんどの賛成票が勝ちます!

出力例を示してください。
ムクルクマール14

@MukulKumarは、これを追加しました
TheDoctor

1
意味がある必要がありますか?または任意の組み合わせ?
ムクルクマール14

それは意味のあるものにする必要はありません
TheDoctor

ユーザーはプログラムを何回まで実行できますか?ある時点で、プログラムはルール#1を破ることはできません。
ミスターリスター14

回答:


8

HTML、CSS、およびJavaScript

HTML

<div id='word-shower'></div>
<div id='letter-container'></div>

CSS

.letter {
    border: 1px solid black;
    padding: 5px;
}

#word-shower {
    border-bottom: 3px solid blue;
    padding-bottom: 5px;
}

JS

var acronym = 'dftba', $letters = $('#letter-container')
for (var i = 0; i < acronym.length; i++) {
    $letters.append($('<div>').text(acronym[i]).attr('class', 'letter'))
}

var $word = $('#word-shower')
setInterval(function() {
    $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://randomword.setgetgo.com/get.php') + '&callback=?', function(word) {
        word = word.contents.toLowerCase()
        $word.text(word)
        $letters.children().each(function() {
            if (word[0] == this.innerText) {
                this.innerText = word
                return
            }
        })
    })
}, 1000)

ランダムな単語ジェネレーターを使用して、単語を探すときにライブ結果を表示します。

自分で実行したい場合のフィドルです。

出力のGIFは次のとおりです。

アニメーション出力


7

Java

ウィクショナリーから単語リストを取得します。そのリストから、正しい文字で始まるランダムな単語を選択します。次に、Googleサジェストを再帰的に使用して、次の単語を探します。可能性のリストを出力します。同じ頭字語で再実行すると、異なる結果が得られます。

import java.io.*;
import java.net.*;
import java.util.*;

public class Acronym {

    static List<List<String>> wordLists = new ArrayList<List<String>>();
    static {for(int i=0; i<26; i++) wordLists.add(new ArrayList<String>());}
    static String acro;

    public static void main(String[] args) throws Exception {
        acro = args[0].toLowerCase();

        //get a wordlist and put words into wordLists by first letter
        String s = "http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/PG/2006/04/1-10000";
        URL url = new URL(s);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            if(inputLine.contains("title")) {
                int start = inputLine.indexOf("title=\"");
                int end = inputLine.lastIndexOf("\">");
                if(start>=0 && end > start) { 
                    String word = inputLine.substring(start+7,end).toLowerCase();
                    if(!word.contains("'") && !word.contains(" ")) {
                        char firstChar = word.charAt(0);
                        if(firstChar >= 'a' && firstChar <='z') {
                            wordLists.get(firstChar-'a').add(word);
                        }
                    }
                }
            }
        }

        //choose random word from wordlist starting with first letter of acronym
        Random rand = new Random();
        char firstChar = acro.charAt(0);
        List<String> firstList = wordLists.get(firstChar-'a');
        String firstWord = firstList.get(rand.nextInt(firstList.size()));

        getSuggestions(firstWord,1);

    }

    static void getSuggestions(String input,int index) throws Exception {
        //ask googleSuggest for suggestions that start with search plus the next letter as marked by index
        String googleSuggest = "http://google.com/complete/search?output=toolbar&q=";
        String search = input + " " + acro.charAt(index);
        String searchSub = search.replaceAll(" ","%20");

        URL url = new URL(googleSuggest + searchSub);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            String[] parts = inputLine.split("\"");
            for(String part : parts) {
                if(part.startsWith(search)) {
                    //now get suggestions for this part plus next letter in acro
                    if(index+1<acro.length()) {
                        String[] moreParts = part.split(" ");
                        Thread.sleep(100);
                        getSuggestions(input + " " + moreParts[index],index+1);
                    }
                    else {
                        String[] moreParts = part.split(" ");
                        System.out.println(input + " " + moreParts[index]);
                    }
                }
            }
        }
        in.close();
    }
}

サンプル出力:

$ java -jar Acronym.jar ght
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horror thriller
great horror tv
great horror thriller
great horror titles
great horror tv
great holiday traditions
great holiday treats
great holiday toasts
great holiday tech
great holiday travel
great holiday treat
great holiday tips
great holiday treat
great holiday toys
great holiday tour
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle

残念ながら、GoogleはURLがしばらくして機能しなくなったことを示唆しています-おそらく、私のIPは誤用のためにGoogleによってブラックリストに登録されたのでしょうか?!


5

ルビー

とてもルビー。多くのドージェ。ワオ。

オンライン版

@prefix = %w[all amazingly best certainly crazily deadly extra ever few great highly incredibly jolly known loftily much many never no like only pretty quirkily really rich sweet such so total terribly utterly very whole xtreme yielding zippily]
@adjective = %w[appealing app apl attractive brave bold better basic common challenge c++ creative credit doge durable dare enticing entertain extreme fail fabulous few favourite giant gigantic google hello happy handy interesting in improve insane jazz joy j java known kind kiwi light laugh love lucky low more mesmerise majestic open overflow opinion opera python power point popular php practice quirk quit ruby read ready stunning stack scala task teaching talking tiny technology unexpected usual useful urban voice vibrant value word water wow where xi xanthic xylophone young yummy zebra zonk zen zoo]

def doge(input)
  wow = ""
  input.chars.each_slice(2) do |char1, char2|
    if char2 == nil
      wow << (@prefix + @adjective).sample(1)[0] + "."
      break
    end
    wow << @prefix.select{|e| e[0] == char1}.sample(1)[0]
    wow << " "
    wow << @adjective.select{|e| e[0] == char2}.sample(1)[0]
    wow << ". "
  end
  wow
end

puts doge("dftba")
puts doge("asofiejgie")
puts doge("iglpquvi")

例:

deadly favourite. terribly better. challenge.
all scala. only favourite. incredibly enticing. jolly giant. incredibly extreme. 
incredibly gigantic. loftily popular. quirkily usual. very interesting.

確かに軽い。今までの声。余分な準備。余分なスタック。とても魅力的です。見事なことはありません。まるごと楽しませる。豊かな見事。お気に入りのみ。驚くほどルビー。
イザベラ14年

致命的な失敗。ひどく勇敢。幸運な。すべてのスカラ。ほんの数。信じられないほど楽しませる。ジョリーグーグル。信じられないほど楽しませる。信じられないほどグーグル。高額のパイソン。風変わりな予想外。非常に改善します。

4

Mathematica

一般に頭字語で使用されるいくつかの用語。

terms = {"Abbreviated", "Accounting", "Acquisition", "Act", "Action", "Actions", "Activities", "Administrative", "Advisory", "Afloat", "Agency", "Agreement", "Air", "Aircraft", "Aligned", "Alternatives", "Analysis", "Anti-Surveillance", "Appropriation", "Approval", "Architecture", "Assessment", "Assistance", "Assistant", "Assurance", "Atlantic", "Authority", "Aviation", "Base", "Based", "Battlespace", "Board", "Breakdown", "Budget", "Budgeting", "Business", "Capabilities", "Capability", "Capital", "Capstone", "Category", "Center", "Centric", "Chairman", "Change", "Changes", "Chief", "Chief,", "Chiefs", "Closure", "College", "Combat", "Command", "Commandant", "Commander","Commander,", "Commanders", "Commerce", "Common", "Communications", "Communities", "Competency", "Competition", "Component", "Comptroller", "Computer", "Computers,", "Concept", "Conference", "Configuration", "Consolidated", "Consulting", "Contract", "Contracting", "Contracts", "Contractual", "Control", "Cooperative", "Corps", "Cost", "Council", "Counterintelligence", "Course", "Daily", "Data", "Date", "Decision", "Defense", "Deficiency", "Demonstration", "Department", "Depleting", "Deployment", "Depot", "Deputy", "Description", "Deskbook", "Determination", "Development", "Direct", "Directed", "Directive", "Directives", "Director", "Distributed", "Document", "Earned", "Electromagnetic", "Element", "Engagement", "Engineer", "Engineering", "Enterprise", "Environment", "Environmental", "Equipment", "Estimate", "Evaluation", "Evaluation)", "Exchange", "Execution", "Executive", "Expense", "Expert", "Exploration", "Externally", "Federal", "Final", "Financial", "Findings", "Fixed","Fleet", "Fleet;", "Flight", "Flying", "Followup", "Force", "Forces,", "Foreign", "Form", "Framework", "Full", "Function", "Functionality", "Fund", "Funding", "Furnished", "Future", "Government", "Ground", "Group", "Guidance", "Guide", "Handbook", "Handling,", "Hazardous", "Headquarters", "Health", "Human", "Identification", "Improvement", "Incentive", "Incentives", "Independent", "Individual", "Industrial", "Information", "Initial", "Initiation", "Initiative", "Institute", "Instruction", "Integrated", "Integration", "Intelligence", "Intensive", "Interdepartmental", "Interface", "Interference", "Internet", "Interoperability", "Interservice", "Inventory", "Investment", "Joint", "Justification", "Key", "Knowledge", "Lead", "Leader", "Leadership", "Line", "List", "Logistics", "Maintainability", "Maintenance", "Management", "Manager", "Manual", "Manufacturing", "Marine", "Master", "Material", "Materials", "Maturity", "Measurement", "Meeting", "Memorandum", "Milestone", "Milestones", "Military", "Minor", "Mission", "Model", "Modeling", "Modernization", "National", "Naval", "Navy", "Needs", "Network", "Networks", "Number", "Objectives", "Obligation", "Observation", "Occupational", "Offer", "Office", "Officer", "Operating", "Operational", "Operations", "Order", "Ordering", "Organization", "Oversight", "Ozone", "Pacific", "Package", "Packaging,", "Parameters", "Participating", "Parts", "Performance", "Personal", "Personnel", "Planning", "Planning,", "Plans", "Plant", "Point", "Policy", "Pollution", "Practice", "Preferred", "Prevention", "Price", "Primary", "Procedure", "Procedures", "Process", "Procurement", "Product", "Production", "Professional", "Program", "Programmatic", "Programming", "Project", "Proposal", "Protection", "Protocol", "Purchase", "Quadrennial", "Qualified", "Quality", "Rapid", "Rate", "Readiness", "Reconnaissance", "Regulation", "Regulations", "Reliability", "Relocation", "Repair", "Repairables", "Report", "Reporting", "Representative", "Request", "Requirement", "Requirements", "Requiring", "Requisition", "Requisitioning", "Research", "Research,", "Reserve", "Resources", "Responsibility", "Review", "Reviews", "Safety", "Sales", "Scale", "Secretary", "Secure", "Security", "Selection", "Senior", "Service", "Services", "Sharing", "Simulation", "Single", "Small", "Software", "Source", "Staff", "Standard", "Standardization", "Statement", "Status", "Storage,", "Strategy", "Streamlining", "Structure", "Submission", "Substance", "Summary", "Supplement", "Support", "Supportability", "Surveillance", "Survey", "System", "Systems", "Subsystem", "Tactical", "Target", "Targets", "Team", "Teams", "Technical", "Technology", "Test", "Tool", "Total", "Training", "Transportation", "Trouble", "Type", "Union", "Value", "Variable", "Warfare", "Weapon", "Work", "Working", "X-Ray", "Xenon", "Year", "Yesterday", "Zenith", "Zoology"};

コード

f[c_]:=RandomChoice[Select[terms,(StringTake[#,1]==c)&]]
g[acronym_]:=Map[f,Characters@acronym]

頭字語ABCのランダムに生成された10個の候補。

Table[Row[g["ABC"], "  "], {10}] // TableForm

アクション内訳軍団
会計予算商務省
航空予算管理
取得内訳コンピューター
アクション予算コスト調整された
内訳共通調整された
予算コース
アドバイザリー予算能力調整されたバトル
スペース共通の
反監視バトルスペースコントローラー


FMP

Table[Row[g["FMP"], "  "], {10}] // TableForm

Findings Managerプロトコル
最終マニュアル購入
飛行測定要員
完全製造計画
フォーム測定プログラミング
財務モデルプログラマティック
将来の近代化提案
財務測定パッケージ
フォーム、保守計画
フルモデリングプログラマティック


STM

Table[Row[g["STM"], "  "], {10}] // TableForm

標準化トータルモダナイゼーション
サービス戦術的なマイルストーン
監視輸送管理
サブシステムトラブル材料
構造テストミリタリー
スケールテスト材料
戦略ツール近代化
小テクノロジーマイナー
サポート輸送製造状況ツール管理


CRPB

Table[Row[g["CRPB"], "  "], {10}] // TableForm

協調規制の保護ビジネス
司令官の要求ポリシーベースの
変更修理プログラミング、事業
閉鎖のレビュープロジェクト予算
商務規制パラメータベース
契約迅速な価格ベース
大学移転実習予算編成
コースレポート人員
バトルスペースコース要件手続き予算


SARDE

Table[Row[g["SARDE"], "  "], {10}] // TableForm

サプリメントアクション指令の見積もり
規模の調整整合要件毎日の見積もり
秘書アトランティック社購買担当ディレクター経費
ソフトウェアアクションレビュー直接探査
サポート法準備防衛電磁
ソフトウェア短縮要件意思決定交換
提出アセスメント申請書説明エグゼクティブ
合理化会計レートデポ評価
サーベイランスアシスタント購買依頼デポエンゲージメント
調査支援リソース


2

D

これはほとんどナンセンスを生み出しますが、時には賢明な何か、またはユーモラスなほど愚かなものを生み出すでしょう。

このJSONファイルから単語が取得されます(最大2.2MB)。

プログラムは、最初のコマンドライン引数から頭字語を取得し、生成するフレーズの数をプログラムに伝えるオプションの2番目の引数をサポートします。

import std.file : readText;
import std.conv : to;
import std.json, std.random, std.string, std.stdio, std.algorithm, std.array, std.range;

void main( string[] args )
{
    if( args.length < 2 )
        return;

    try
    {
        ushort count = 1;

        if( args.length == 3 )
            count = args[2].to!ushort();

        auto phrases = args[1].toUpper().getPhrases( count );

        foreach( phrase; phrases )
            phrase.writeln();
    }
    catch( Throwable th )
    {
        th.msg.writeln;
        return;
    }
}

string[] getPhrases( string acronym, ushort count = 1 )
in
{
    assert( count > 0 );
}
body
{
    auto words = getWords();
    string[] phrases;

    foreach( _; 0 .. count )
    {
        string[] phrase;

        foreach( chr; acronym )
        {
            auto matchingWords = words.filter!( x => x[0] == chr ).array();
            auto word = matchingWords[uniform( 0, matchingWords.length )];
            phrase ~= word;
        }

        phrases ~= phrase.join( " " );
    }

    return phrases;
}

string[] getWords()
{
    auto text = "words.json".readText();
    auto json = text.parseJSON();
    string[] words;

    if( json.type != JSON_TYPE.ARRAY )
        throw new Exception( "Not an array." );

    foreach( item; json.array )
    {
        if( item.type != JSON_TYPE.STRING )
            throw new Exception( "Not a string." );

        words ~= item.str.ucfirst();
    }

    return words;
}

auto ucfirst( inout( char )[] str )
{
    if( str.length == 1 )
        return str.toUpper();

    auto first = [ str[0] ];
    auto tail  = str[1 .. $];

    return first.toUpper() ~ tail.toLower();
}

D:\Code\D\Acronym>dmd acronym.d

D:\Code\D\Acronym>acronym utf 5
Unchallenged Ticklebrush Frication
Unparalysed's Toilsomeness Fructose's
Umpiring Tableland Flimsily
Unctuousness Theseus Flawless
Umbrella's Tarts Formulated

2

バッシュ

for char in $(sed -E s/'(.)'/'\1 '/g <<<"$1");
do
    words=$(grep "^$char" /usr/share/dict/words)
    array=($words)
    arrayCount=${#array[*]}
    word=${array[$((RANDOM%arrayCount))]}
    echo -ne "$word " 
done
echo -ne "\n"

ので:$ bash acronym-to-phrase.sh dftba結果

deodorization fishgig telolecithal bashlyk anapsid
demicivilized foretell tonogram besmouch anthropoteleological
doer fightingly tubulostriato bruang amortize 


そして:$ bash acronym-to-phrase.sh diy結果として

decanically inarguable youthen
delomorphous isatin yen
distilling inhumorously yungan


最後に: $ bash acronym-to-phrase.sh rsvp

retzian sensitizer vestiarium pathognomonical
reaccustom schreiner vincibility poetizer
refractorily subspherical villagey planetule

...

私の最初の反応は?無力なトランスポートファイアリング


1

Python

したがって、これはおそらく人気コンテストには勝てないでしょうが、私はPythonに表現が必要だと考えました。これはPython 3.3以降で機能します。@ tony-hのjsonの単語のファイルを借りました(ここにあります)。基本的に、このコードはjsonリストを取得し、すべての単語をアルファベットの文字で索引付けされた辞書に編成します。次に、Pythonアプリケーションに渡される頭字語はすべて、辞書のインデックスとして使用されます。頭字語の各文字について、その文字の下にインデックス付けされたすべての単語からランダムな単語が選択されます。必要な数の出力を提供することもできます。何も指定しない場合、2つのオプションが生成されます。

コード(phraseit.pyとして保存しました):

import argparse
import json
import string
from random import randrange

parser = argparse.ArgumentParser(description='Turn an acronym into a random phrase')
parser.add_argument('acronym', nargs=1)
parser.add_argument('iters',nargs='?',default=2,type=int)
args = parser.parse_args()

acronym=args.acronym[0]
print('input: ' + acronym)

allwords=json.load(open('words.json',mode='r',buffering=1))

wordlist={c:[] for c in string.ascii_lowercase}
for word in allwords:
    wordlist[word[0].lower()].append(word)

for i in range(0,args.iters):
    print('output:', end=" ")
    for char in acronym:
        print(wordlist[char.lower()][randrange(0,len(wordlist[char.lower()]))], end=" ")
    print()

いくつかのサンプル出力:

$ python phraseit.py abc
input: abc
output: athabaska bookish contraster
output: alcoholism bayonet's caparison

別の:

$ python phraseit.py gosplet 5
input: gosplet
output: greenware overemphasiser seasons potential leprosy escape tularaemia
output: generatrix objectless scaloppine postulant linearisations enforcedly textbook's
output: gutturalism oleg superstruct precedential lunation exclusion toxicologist
output: guppies overseen substances perennialises lungfish excisable tweed
output: grievously outage Sherman pythoness liveable epitaphise tremulant

最後に:

$ python phraseit.py nsa 3
input: nsa
output: newsagent spookiness aperiodically
output: notecase shotbush apterygial
output: nonobjectivity sounded aligns
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.