Akronim ke frasa


12

Tugas:

Buat program yang akan mengambil akronim sebagai input, misalnya dftba, dan menghasilkan beberapa frasa yang mungkin singkatan dari singkatan tersebut. Anda dapat menggunakan daftar kata sebagai input kata. Terinspirasi oleh https://www.youtube.com/watch?v=oPUxnpIWt6E

Contoh:

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

Aturan:

  • Program Anda tidak dapat menghasilkan frasa yang sama setiap kali untuk akronim yang sama, harus ada pengacakan
  • Input semua huruf kecil
  • Posting beberapa contoh (input dan output)
  • Bahasa apa pun diterima
  • Ini adalah , sehingga sebagian besar pemenang menang!

Tolong tunjukkan contoh output.
Mukul Kumar

@MukulKumar menambahkannya
TheDoctor

1
Perlu bermakna? atau kombinasi apa pun?
Mukul Kumar

Tidak perlu bermakna
TheDoctor

Berapa kali pengguna diizinkan untuk menjalankan program? Pada titik tertentu program tidak bisa tidak melanggar aturan # 1.
Tuan Lister

Jawaban:


8

HTML, CSS, dan 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)

Menggunakan generator kata acak dan menunjukkan hasil langsung saat mencari kata-kata.

Ini biola jika Anda ingin menjalankannya sendiri.

Berikut adalah GIF dari hasilnya:

output animasi


7

Jawa

Mengambil daftar kata dari wiktionary. Memilih kata acak dari daftar yang dimulai dengan huruf yang benar. Kemudian gunakan Google sarankan secara rekursif untuk mencari kemungkinan kata berikutnya. Keluarkan daftar kemungkinan. Jika Anda menjalankannya kembali dengan akronim yang sama, Anda akan mendapatkan hasil yang berbeda.

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();
    }
}

Output sampel:

$ 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

Sayangnya, Google menyarankan URL berhenti berfungsi setelah beberapa saat - mungkin IP saya dimasukkan daftar hitam oleh Google karena salah gunakan ?!


5

Rubi

sangat ruby. banyak doge. Wow.

Versi Online

@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")

Contoh:

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

tentu saja ringan. pernah bersuara. ekstra siap. tumpukan ekstra. sangat menarik. tidak pernah menakjubkan. Seluruh menghibur. kaya yang menakjubkan. hanya favorit. ruby luar biasa.
izabera

gagal mematikan. sangat berani. beruntung. semua scala. hanya beberapa. sangat menghibur. riangnya google. sangat menghibur. luar biasa google. python tinggi. sangat tidak terduga. sangat meningkat.

4

Mathematica

Beberapa istilah yang biasa muncul dalam akronim.

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"};

Kode

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

Contohnya

Sepuluh kandidat yang dihasilkan secara acak untuk akronim ABC .

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

Aksi Breakdown Korps
Akuntansi Anggaran Commerce
Air Penganggaran Kontrol
Akuisisi Breakdown Komputer
tindakan Anggaran Biaya
Blok Breakdown umum
Blok Penganggaran Course
Penasehat Penganggaran Kemampuan
Blok Battlespace umum
Anti-Surveillance Battlespace Comptroller


FMP

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

Temuan-temuan Manajer Protokol
Manual Akhir Pembelian
Personel Pengukuran Terbang Personil
Bidang Pabrikan Penuh
Formulir Pengukuran Pemrograman
Model Keuangan Programmatic
Masa Depan Modernisasi Proposal Formulir
Paket Pengukuran Keuangan
, Perencanaan Pemeliharaan
Pemodelan Lengkap Programmatic


STM

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

Standardisasi Total
Layanan Modernisasi Milestone Taktis
Pengawasan Manajemen Transportasi
Subsistem Masalah Bahan
Uji Struktur
Skala Militer Bahan Uji
Strategi Alat Modernisasi
Teknologi Kecil
Dukungan Kecil Transportasi Status Manufaktur Manajemen Alat


CRPB

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

Perlindungan Peraturan Kerjasama
Komandan Bisnis Permintaan Kebijakan
Perubahan Pangkalan Perbaikan Pemrograman,
Tinjauan Penutupan Bisnis Anggaran Proyek
Peraturan Perdagangan Parameter Dasar
Kontrak Cepat Harga Dasar
Perguruan Tinggi Praktek Penganggaran
Kursus Pelaporan Personil Battlespace
Course Persyaratan Prosedur Prosedur Anggaran


SARDE

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

Tindakan Tambahan yang Memerlukan Arahan
Skala Perkiraan Persyaratan yang
Diperlukan Sekretaris Perkiraan Harian Direktur Perolehan Atlantik Pengeluaran
Perangkat Lunak Tinjauan Tindakan
Dukungan Langsung Kesiapan Pertahanan
Perangkat Lunak Elektromagnetik Disingkat Persyaratan Pengambilan Keputusan Pertukaran
Pengajuan Penilaian Permintaan Deskripsi Eksekutif
Perampingan Akuntansi Tingkat Akuntansi Depot Evaluasi
Surveillance Assistant Asisten Penempatan Depot Keterlibatan
Survei Survei Sumber Daya Bantuan Defisiensi Biaya Sumber Daya


2

D

Ini sebagian besar menghasilkan omong kosong, tetapi kadang-kadang akan menghasilkan sesuatu yang masuk akal, atau sesuatu yang sangat konyol untuk menjadi lucu.

Kata-kata ditarik dari file JSON ini (~ 2.2MB).

Program mengambil akronim dari argumen baris perintah pertama, dan mendukung argumen kedua opsional yang memberitahu program berapa banyak frasa yang akan dihasilkan.

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();
}

Contoh :

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

PESTA

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"

Jadi: $ bash acronym-to-phrase.sh dftbamenghasilkan

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


Dan: $ bash acronym-to-phrase.sh diymenghasilkan

decanically inarguable youthen
delomorphous isatin yen
distilling inhumorously yungan


Akhirnya: $ bash acronym-to-phrase.sh rsvp

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

...

Reaksi awal saya? firel transportal tanpa dasar


1

Python

Jadi, ini mungkin tidak akan memenangkan kontes popularitas, tapi saya pikir Python membutuhkan representasi. Ini berfungsi dalam Python 3.3+. Saya meminjam file kata json @ tony-h ( temukan di sini ). Pada dasarnya, kode ini hanya mengambil daftar json, dan mengatur semua kata ke dalam kamus yang diindeks pada huruf-huruf alfabet. Kemudian, akronim apa pun yang dilewatkan ke dalam aplikasi python digunakan sebagai indeks ke dalam kamus. Untuk setiap huruf dalam akronim, kata acak dipilih dari semua kata yang diindeks di bawah surat itu. Anda juga dapat memberikan sejumlah output yang diinginkan, atau jika tidak ada yang ditentukan, 2 opsi akan dihasilkan.

Kode (saya menyimpannya sebagai phrit.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()

Beberapa output sampel:

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

Lain:

$ 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

Akhirnya:

$ python phraseit.py nsa 3
input: nsa
output: newsagent spookiness aperiodically
output: notecase shotbush apterygial
output: nonobjectivity sounded aligns
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.