首字母缩略词短语


12

任务:

例如dftba,创建一个将首字母缩略词作为输入的程序,并生成一些可能的缩写词代表的短语。您可以将单词表用作单词输入。受https://www.youtube.com/watch?v=oPUxnpIWt6E的启发

例:

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

规则:

  • 您的程序无法每次使用相同的首字母缩略词生成相同的词组,因此必须进行随机化
  • 输入将全部为小写
  • 发布一些示例(输入和输出)
  • 接受任何语言
  • 这是一场,因此大多数投票都获胜!

请显示示例输出。
Mukul Kumar'3

@MukulKumar添加了它
TheDoctor 2014年

1
需要有意义吗?或任何组合?
Mukul Kumar'3

它不需要是有意义的
TheDoctor

允许用户运行该程序多少次?在某些时候,该程序不得不违反规则1。
李斯特先生2014年

Answers:


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

爪哇

从维基词典中提取单词列表。从该列表中选择一个以正确字母开头的随机单词。然后使用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

不幸的是,谷歌建议URL在​​一段时间后停止工作-也许我的IP因滥用而被黑名单了?


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.

当然轻。曾经的声音。额外准备。额外的堆栈。极具吸引力。永不惊艳。整个娱乐。丰富的令人惊叹。唯一喜欢的。惊人的红宝石。
izabera 2014年

致命的失败。非常勇敢。幸运。所有斯卡拉。只有少数。令人难以置信的娱乐。欢乐谷歌。令人难以置信的娱乐。谷歌。高高地蟒蛇。出乎意料的意外。非常好。

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候选词。

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

合作规章保护业务
司令员要求政策基础
变更维修计划,业务
闭幕审查项目预算
商业法规参数基础
合同快速价格基础
大学搬迁实践预算
课程报告人员战场
课程需求程序预算


萨德

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

要求指令的补充行动估计
规模统一要求每日估计
秘书大西洋需求主管支出
软件行动审查直接勘探
支持法准备就绪防卫电磁
软件缩略的需求决策交换
提交评估评估需求描述执行人员
精简计费率仓库评估
监控助理需求仓库投入参与
调查协助资源短缺费用


2

d

这主要产生胡说八道,但偶尔也会产生明智的事情,或愚蠢到幽默的事情。

从此JSON文件(〜2.2MB)中提取单词。

程序从第一个命令行参数中获取首字母缩写词,并支持一个可选的第二个参数,该参数告诉程序要生成多少个短语。

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 3.3+。我借用了@ tony-h的json单词文件(在这里找到它)。基本上,此代码仅接收json列表,并将所有单词组织到按字母顺序索引的字典中。然后,将传递给python应用程序的首字母缩写词用作字典的索引。对于首字母缩写词中的每个字母,从该字母下索引的所有单词中选择一个随机单词。您还可以提供所需的多个输出,或者,如果未指定任何内容,将生成2个选项。

代码(我将其保存为phrase.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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.