สร้างประโยคที่เข้าใจได้


55

ปัญหา:

สร้างประโยคที่สามารถอ่านและเข้าใจได้ มันจะต้องมีหัวเรื่องคำกริยาและวัตถุและกาลและพหูพจน์ต้องตรงกัน โปรแกรมจะต้องสามารถสร้างประโยคที่แตกต่างหลากหลายเพื่อให้มีคุณสมบัติ

กฎ:

  • ไม่อนุญาตให้เขียนโค้ดอย่างหนักและไม่อ่านจากไฟล์โดยตรง (ฉันกำลังดูคุณอยู่ไม่สะอาด)
  • คุณสามารถมีรายการคำศัพท์จำนวนเท่าใดก็ได้
  • ส่งประโยคตัวอย่างหรือ 2 ที่โปรแกรมของคุณสร้างขึ้น
  • ยอมรับภาษาใดก็ได้
  • มันเป็นการดังนั้นคำตอบที่ได้รับการโหวตมากที่สุดจะเป็นผู้ชนะ

7
ฉันคิดว่ามันชัดเจนจากคำตอบบางส่วน ( MatLab ที่ฉันมองคุณ) ว่าคุณควรปรับเปลี่ยนกฎเพื่อไม่ให้มีการขุดข้อมูลเพื่อดึงคำที่ต่อเนื่องมาจากแหล่งใด ๆ
Carl Witthoft

ในขณะที่ฉันเป็นคนฉลาด: เนื่องจากเป็นการประกวดความนิยมอย่างหมดจดบางคนควรโพสต์ jpg HotModelBikini นั่นจะได้รับคะแนนเสียงมากกว่าทุกอย่าง
Carl Witthoft

7
ฉันจะโหวตใครก็ได้ที่ใช้คำว่า "ควาย" หรือ "ปลา" ซ้ำเป็นประโยค!

7
คำตอบส่วนใหญ่ที่นี่ทั้งที่ถูกต้องประโยคเต็มจากแหล่งข้อความหรือสร้างผลลัพธ์ที่ไม่ตรงตามเกณฑ์ สำหรับฉันแล้วทั้งสองวิธีดูเหมือนขัดกับวิญญาณของคำถาม! หากมีคนต้องการสร้างความประทับใจจริงๆฉันขอแนะนำโปรแกรมที่เริ่มต้นด้วยโครงสร้างประโยคที่ถูกต้องเช่น[Adjective] [pl. noun] [verb] [adjective] [pl. noun]และดึงจากพจนานุกรมจริง (อาจใช้หนึ่งใน API ของพจนานุกรมที่มีอยู่ที่นั่น) เติมลงในช่องว่าง? ฉันจะเขียนเองถ้าฉันมีเวลาไม่กี่นาที! :( หลังจากทั้งหมด ...Lazy Developers Write Lousy Programs.
Brian Lacy

1
@Pureferret Word รายการจะเป็นรายการของคำแต่ละคำ การเข้ารหัสฮาร์ดจะเป็นรายการของประโยคที่สมบูรณ์ ด้วยรายการคำโดยทั่วไปคุณจะต้องใช้ตรรกะบางอย่างในโปรแกรมเพื่อรวมประโยคที่สมบูรณ์ ด้วยประโยคที่เขียนโค้ดยากคุณเพียงแค่ต้องการพิมพ์คำสั่ง
8bittree

คำตอบ:


87

ทุบตี

fgrep '/* ' /usr/src/linux* -r | cut -d '*' -f 2 | head -$((RANDOM)) | tail -1

ความต้องการ: แหล่งเคอร์เนล linux ติดตั้งใน / usr / src

สิ่งนี้จะดึงความคิดเห็นแบบสุ่มออกมาจากเคอร์เนลซอร์ส ประโยคที่เข้าใจได้จริงหรือไม่นั้นเปิดให้มีการถกเถียงกัน

ตัวอย่างของเอาต์พุตจริง:

  • end of packet for rx
  • I don't know what to do
  • 256 byte packet data buffer.
  • The rest of this junk is to help gdb figure out what goes where
  • Convert page list back to physical addresses, what a mess.
  • ???
  • Only Sun can take such nice parts and fuck up the programming interface

12
สิ่งที่ดี! คุณควรดึงพวกเขาทั้งหมดและส่งเป็นfortuneฐานข้อมูลอย่างเป็นทางการ
Jason C

18
"???" ความคิดเห็นที่ดีที่สุดตลอดกาล
Ray

4
ไม่ใช่กฎอันดับแรก 'และไม่อ่านพวกเขาโดยตรงจากไฟล์' ถูกละเมิด?
kuldeep.kamboj

6
ฉันว่าการค้นหาผ่านซอร์สโค้ดของระบบและการกรองข้อความจากความคิดเห็นไม่ได้นับว่าเป็น "การอ่านโดยตรง"
Riot

7
Slave Overflowและ ชื่อที่ดีสำหรับเว็บไซต์ SE
TheDoctor

95

Matlab

why

ตัวอย่างของผลลัพธ์:

>> why
The programmer suggested it.
>> why
To please a very terrified and smart and tall engineer.
>> why
The tall system manager obeyed some engineer.
>> why
He wanted it that way.

[นี่คือหนึ่งในไข่อีสเตอร์ของ Matlab]

แก้ไข:คุณสามารถดูรหัสของฟังก์ชั่นนี้ได้ที่นี่: ทำไม


3
คุณสามารถดูรหัสได้ที่นี่: opg1.ucsd.edu/~sio221/SIO_221A_2009/SIO_221_Data/Matlab5/ …
Elisha

8
ตัวอย่างที่สองไม่ใช่ประโยค มันเป็นวลีที่ไม่มีที่สิ้นสุด
wchargin

2
ต้องมีคำตอบที่นี่ไม่เพียง แต่สร้างประโยคเท่านั้น งานไม่ได้บอกว่ามันจะต้องสร้างเพียงประโยค แต่มันบอกว่ามันจะต้องสามารถสร้างประโยคได้
เอลีชา

51

PHP

ให้เวลาเพียงพอสิ่งนี้จะผลิตงานวรรณกรรมทั้งในอดีตปัจจุบันและอนาคต กฎไม่ได้กล่าวถึงว่าอาจไม่มีการสร้างข้อความอื่น

สตริง'TOS...'ให้ความถี่สเกลลอการิทึมของตัวอักษรเพื่อให้ตรงกับภาษาอังกฤษมากขึ้น สิ่งนี้ใช้เพื่อสร้างสตริงที่มีขนาดใหญ่ขึ้นพร้อมกับความถี่จดหมายโดยประมาณ

$a = ord('A');
$s = '';

foreach (str_split('TOSRWQPPUALRQTTRGUUUQMMLMFZ') as $i=>$f)
{
    if (!ctype_alpha($c = chr($a + $i)))
        $c = ' ';
    $s .= str_repeat($c, round(exp((ord($f) - $a) / 3.976)));
}

$l = strlen($s) - 1;
for (;;)
    echo substr($s, mt_rand(0, $l), 1);

ฉันได้ค้นพบอัญมณีวรรณกรรมเช่น:

  • GO NOW- คุณเป็นหัวข้อที่บอกเป็นนัย
  • IM AOK - ฉันก็โอเค
  • IM FDR - ฉัน F (อันดับ) D (eleano) R (oosevelt)

นอกจากนี้นักปราชญ์จำนวนมากยังแสดงความไม่พอใจอย่างรัดกุมต่อสถานการณ์ปัจจุบัน [ตัวอักษรบางตัวถูกใส่เข้าไปใหม่]

  • F**K
  • S**T

เช่นกันการใช้มาตราส่วนแบบละเอียด:

  • IS IT ON
  • I AM STU
  • I SEE HTML

60
ทำไมลิงจำนวนหนึ่งก็ทำแบบเดียวกันได้!
Tim S.

11
ฉันชอบ! ตอนนี้ทำโปรแกรมที่ประมวลผลตัวอักษรที่ออกมาจากนั้นและหาประโยคที่เข้าใจได้! :)
TheDoctor

2
+1 - โอกาสใดที่จะทำให้ส่วนที่ค้นพบเป็นอัตโนมัติ? งานดูเหมือนจะสร้างประโยค * หนึ่ง * (?) BTW: คุณใช้เวลาเท่าไหร่;)
Wolf

20
คุณได้รับF**KและS**Tให้สิ่งที่ไม่มี*ในได้'ABCDEFGHIJKMLNOPQRSTUVWXYZ 'อย่างไร?
glglgl

3
@Ypnypn - 'TOS...'สตริงแสดงความถี่ของตัวอักษรแต่ละตัวในระดับลอการิทึม ดังนั้นAมีความถี่T, มีความถี่B มีความถี่ต่ำสุดซึ่งแปลเป็น 0 ซึ่งบันทึกผกผันคือ 1. ตัวอักษรตัวสุดท้ายคือพื้นที่ซึ่งมีความถี่หรือรอบ (exp (25 / 3.976)) = 538 ดังนั้นช่องว่างที่เกิดขึ้น 538 ครั้งบ่อยกว่า แค่คิดว่ามันทำให้เกิดปัญหากับเครื่องพิมพ์ดีด OJAZJ

42

C

char*strerror(),i;main(){for(;--i;)puts(strerror(i));}

ตัวอย่างผลลัพธ์:

ซอฟต์แวร์ที่ทำให้เกิดการเชื่อมต่อยกเลิกการ
เรียกใช้ระบบที่ถูกขัดจังหวะควรเริ่มใหม่

นอกจากนี้ยังมีเอาต์พุตประโยคที่ถูกต้องจำนวนมากที่ไม่มีหัวเรื่องคำกริยาและวัตถุ:


ไฟล์ตัวจับเวลาหมดอายุแล้ว


สิ่งนี้จะสิ้นสุดได้อย่างไรและเมื่อไหร่? (มันเป็นเช่นนั้น แต่ฉันไม่เข้าใจว่าทำไม)
phil294

1
@Blauhirn เงื่อนไขการสิ้นสุดลูปจะ--iประเมินเป็นเท็จเมื่อi(ตัวแปรชนิดที่charมีค่าเริ่มต้น 0) ถึง 0 อีกครั้ง หากcharไม่ได้ลงชื่อ (เช่น ARM) iจะห่อรอบค่าที่ใหญ่ที่สุดทันที (โดยทั่วไปคือ 255) และนับถอยหลังเป็น 0 หากcharลงชื่อ (ระบบ Intel ส่วนใหญ่) พฤติกรรมนั้นพูดอย่างไม่ได้กำหนด แต่โดยปกติเมื่อถึงค่าต่ำสุดแล้ว ( โดยทั่วไปแล้ว -128) มันจะล้อมรอบไปจนถึงสูงสุด (โดยปกติ 127) และนับถอยหลังเป็น 0 ดังนั้นโปรแกรมจะพิมพ์ 256 บรรทัดโดยรวม
ecatmur

37

ชวา

ดึงประโยคคำนำจากบทความ Wikipedia แบบสุ่ม:

import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class RandomSentence {
    public static void main (String[] args) throws Exception {
        String sentence;
        do {
            InputStream in = new URL("https://en.wikipedia.org/wiki/Special:Random").openStream();
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
            String intro = doc.getElementsByTagName("p").item(0).getTextContent();
            sentence = intro.replaceAll("\\([^(]*\\) *", "").replaceAll("\\[[^\\[]*\\]", "").split("\\.( +[A-Z0-9]|$)")[0];
        } while (sentence.endsWith(":") || sentence.length() < 30 || sentence.contains("?"));
        System.out.println(sentence + ".");
    }
}

บางครั้งคุณก็โชคร้าย ฉันพยายามลดสิ่งนี้โดยการตั้งค่าความยาวประโยคขั้นต่ำและกรองประโยคที่ลงท้ายด้วย ":" (หน้าแก้ความกำกวมทั้งหมดเริ่มต้นด้วยวิธีนั้น) หรือมี "?" (ดูเหมือนจะมีหลายบทความที่มีข้อมูลที่ไม่รู้จักที่ยังไม่ได้แก้ไขซึ่งถูกทำเครื่องหมายด้วยเครื่องหมายคำถาม) ขอบเขตประโยคเป็นระยะเวลาตามด้วยช่องว่างตามด้วยตัวเลขหรือตัวพิมพ์ใหญ่

ฉันยังกรองข้อความในวงเล็บ (ผลลัพธ์ยังคงเป็นประโยคที่ถูกต้อง) เพื่อลองและลบบางช่วงที่ไม่ใช่ขอบเขตประโยค ฉันกรองเครื่องหมายวงเล็บเหลี่ยมเพื่อลบหมายเลขอ้างอิงแหล่งที่มา ตัวอย่าง:

  • Idle Cure เป็นวงดนตรีร็อคชื่อดังจากลองบีชแคลิฟอร์เนีย
  • การโฟกัสด้วยตนเองเป็นกระบวนการออปติคัลแบบไม่เชิงเส้นเนื่องจากการเปลี่ยนแปลงของดัชนีการหักเหของวัสดุที่สัมผัสกับรังสีแม่เหล็กไฟฟ้า
  • TB10Cs4H3 เป็นสมาชิกของคลาส R / H ที่มีลักษณะคล้าย H / ACA ของโมเลกุล RNA ที่ไม่มีการเข้ารหัส
  • Wild Ram หกหัวในตำนานซูเป็นหนึ่งในวีรบุรุษที่ถูกสังหารโดย Ninurta เทพผู้อุปถัมภ์ของ Lagash ในอิรักโบราณ
  • Sugar daddy เป็นคำแสลงสำหรับผู้ชายที่เสนอให้การสนับสนุนผู้หญิงที่อายุน้อยกว่าหรือชายหลังจากสร้างความสัมพันธ์ที่มักจะมีเพศสัมพันธ์
  • Old Bethel United Methodist Church ตั้งอยู่ที่ 222 Calhoun St. , ชาร์ลสตัน, เซาท์แคโรไลนา
  • Douglas Geers เป็นนักแต่งเพลงชาวอเมริกัน

หากคุณสังเกตเห็นปัญหาไวยากรณ์ใด ๆ นั่นเป็นความผิดของคุณที่ไม่ได้เป็นบรรณาธิการวิกิพีเดียที่ขยัน! ;-)


4
มีความแตกต่างระหว่าง "ใช้ได้" และ "เข้าใจได้" อย่างแน่นอน ฉันมี pseudouridines RNA ของสารตั้งต้นสำหรับคุณที่นี่ที่รัก
Jason C

1
ฉันได้สิ่งนี้เป็นครั้งแรกที่ฉันวิ่ง: Echinolittorina africana / Litorina africana Philippi, 1847 / Litorina decollata Philippi, 1847 / Littorina africana / Littorina perplexa Turton, 1932 / Nodilittorina africana / ดูเหมือนว่าจะมีหน้าวิกิพีเดียบางหน้าที่คุณควรยกเว้น ค้นหา! ;) ฮ่าฮ่า! OMG เป็นครั้งที่สองที่ฉันวิ่งมันส่งคืนบรรทัดจากหน้า Wiki ของ Mikhail Gorbachev แบ่งปันชื่อของฉันใคร ค่อนข้างนอกลู่นอกทาง
mikhailcazi

2
'/' ไม่ได้อยู่ที่นั่นจริงๆ! ฮ่าฮ่า: PI ใช้มันเพื่อแสดงบรรทัดใหม่ บางทีฉันควรจะใช้ \ n มันมาจากที่นี่: en.wikipedia.org/wiki/Afrolittorina_africana ตารางด้านขวาภายใต้คำพ้องความหมาย :) อย่างไรก็ตามมันไม่ได้เป็นความประทับใจที่ดีดังนั้นไม่ต้องกังวลเพราะมิคาอิลกอร์บาชอฟเป็นสิ่งที่ค่อนข้างดี และประโยคทั้งหมดหลังจากนั้นเป็นเรื่องปกติ
mikhailcazi

2
คุณอาจพบว่าฟิสิกส์นี้ตอบผู้ใช้ร่วมที่น่าสนใจเมื่อเร็ว ๆ นี้ของหนึ่งในบทความเหล่านั้น
EP

2
อาจเป็นหนึ่งในความน่าจะเป็นที่พบได้ทั่วไป แต่ไม่ได้เกิดขึ้นได้ง่ายมากเหตุการณ์ครั้งหนึ่งในล้านเกิดขึ้นได้ค่อนข้างบ่อยในโลกที่มีผู้คนหลายพันล้านคน ที่กล่าวว่าฉันไม่แน่ใจว่าสิ่งที่การวิเคราะห์อย่างเป็นทางการจะพูด ฉันก็ประหลาดใจมาก! คุณอาจสังเกตว่าไม่มี 'คนอื่น' ที่เกี่ยวข้อง
EP

34

Soooo ... เนื่องจากเป็นการฉันจึงสนุกไปevalกับฟังก์ชั่น โดยทั่วไปฉันสร้างตัวเลขสุ่มแล้วรันฟังก์ชั่นแบบสุ่มขึ้นอยู่กับจำนวนที่ (ในใบหน้าของคุณswitch!) evalผ่าน

PHP, ผลลัพธ์ที่ถูกต้อง ~ 9k

<?php

//Subjects
function s1(){ echo "I "; $m = rand(1,20); eval ("v".$m."(0);");}
function s2(){ echo "You "; $m = rand(1,20); eval ("v".$m."(0);");}
function s3(){ echo "He "; $m = rand(1,20); eval ("v".$m."(1);");}
function s4(){ echo "She "; $m = rand(1,20); eval ("v".$m."(1);");}
function s5(){ echo "We "; $m = rand(1,20); eval ("v".$m."(0);");}
function s6(){ echo "They "; $m = rand(1,20); eval ("v".$m."(0);");}

//Verbs
function v1($n){ echo "want"; if($n==1)echo"s"; echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v2($n){ echo "need"; if($n==1)echo"s"; echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v3($n){ echo "ha"; if($n==1){echo"s";}else{echo"ve";} echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v4($n){ echo "wanted to "; $z = rand(1,10); eval ("a".$z."();");}
function v5($n){ echo "needed to "; $z = rand(1,10); eval ("a".$z."();");}
function v6($n){ echo "had to "; $z = rand(1,10); eval ("a".$z."();");}
function v7($n){ echo "eat"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v8($n){ echo "think"; if($n==1)echo"s"; echo " about "; $w = rand(1,20); eval ("o".$w."();");}
function v9($n){ echo "ate "; $w = rand(1,20); eval ("o".$w."();");}
function v10($n){ echo "thought about "; $w = rand(1,20); eval ("o".$w."();");}
function v11($n){ echo "draw"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v12($n){ echo "drew "; $w = rand(1,20); eval ("o".$w."();");}
function v13($n){ echo "smell"; if($n==1)echo"s"; echo " like "; $w = rand(1,20); eval ("o".$w."();");}
function v14($n){ echo "shot "; $w = rand(1,20); eval ("o".$w."();");}
function v15($n){ echo "destroy"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v16($n){ echo "destroyed "; $w = rand(1,20); eval ("o".$w."();");}
function v17($n){ echo "melt"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v18($n){ echo "saw "; $w = rand(1,20); eval ("o".$w."();");}
function v19($n){ echo "ha"; if($n==1){echo"s";}else{echo"ve";} echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v20($n){ echo "had "; $w = rand(1,20); eval ("o".$w."();");}

//Auxiliaries
function a1(){ echo "punch "; $w = rand(1,20); eval ("o".$w."();");}
function a2(){ echo "drive "; $w = rand(1,20); eval ("o".$w."();");}
function a3(){ echo "mount "; $w = rand(1,20); eval ("o".$w."();");}
function a4(){ echo "see "; $w = rand(1,20); eval ("o".$w."();");}
function a5(){ echo "have "; $w = rand(1,20); eval ("o".$w."();");}
function a6(){ echo "eat "; $w = rand(1,20); eval ("o".$w."();");}
function a7(){ echo "stun "; $w = rand(1,20); eval ("o".$w."();");}
function a8(){ echo "kiss "; $w = rand(1,20); eval ("o".$w."();");}
function a9(){ echo "Ted "; $w = rand(1,20); eval ("o".$w."();");} //See "How I met Your Mother" for further informations :)
function a10(){ echo "blow "; $w = rand(1,20); eval ("o".$w."();");}

//Objects
function o1(){ echo "a cow!<br>";}
function o2(){ echo "a meatball!<br>";} 
function o3(){ echo "a car!<br>";} 
function o4(){ echo "shoes!<br>";} 
function o5(){ echo "pigs!<br>";} 
function o6(){ echo "a telephone!<br>";} 
function o7(){ echo "some bottles of water!<br>";} 
function o8(){ echo "a laptop!<br>";} 
function o9(){ echo "my shorts!<br>";} //Quote needed
function o10(){ echo "anchovies!<br>";}
function o11(){ echo "an alarm clock!<br>";}
function o12(){ echo "every second!<br>";}
function o13(){ echo "until the end!<br>";}
function o14(){ echo "sitting!<br>";}
function o15(){ echo "a sword!<br>";}
function o16(){ echo "fire!<br>";}
function o17(){ echo "the dust!<br>";}
function o18(){ echo "in the bedroom!<br>";}
function o19(){ echo "a poor ant!<br>";}
function o20(){ echo "a pencil!<br>";}

//Testing
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");

?>

เอาท์พุทบาง ...

She draws a sword!
They thought about sitting!
You eat my shorts!
He wanted to Ted a cow!
You want to mount a poor ant!
She smells like anchovies!
He wanted to have shoes!
They wanted to see a pencil!

@ nyuszika7h PHP_EOLมีค่าเท่ากัน\nหรือ\r\nขึ้นอยู่กับระบบปฏิบัติการ แต่ไม่เคย<br>หรือคล้ายกัน
timmyRS

@timmyRS ใช่คุณพูดถูกนี่เป็นความคิดเห็นเก่าฉันไม่รู้ว่าทำไมฉันถึงเขียนตอนนั้น
nyuszika7h

33

PHP + โครงการกูเทนแบร์ก

ฉันเขียนสคริปต์ PHP ที่เปลี่ยนเอกสารข้อความธรรมดาให้เป็นชุดคำขนาดใหญ่ซึ่งจะใช้ในการสร้างประโยคแบบสุ่ม นี่คือตัวอย่างที่ดีกว่าที่สร้างขึ้นจากคำพูด "Give Me Liberty or Give Me Death"ของแพทริกเฮนรี่ทั้งหมดรวมถึงการพิมพ์ขนาดเล็กของโครงการกูเทนแบร์ก:

  • The Project Gutenberg เป็นต้นกำเนิดของชาติต่าง ๆ และการเป็นทาส!

  • เราขออภัยที่ครบรอบ 200 ปีของการพิมพ์ขนาดเล็กนี้!

  • คุณไม่มีการรับประกันใด ๆ ไม่ว่าจะเป็นความเสียหายทางด่วนหรือความเสียหายใด ๆ แต่สำหรับฉันความตาย!

คุณสามารถลองด้วยตัวเองที่นี่ รีเฟรชหน้าสำหรับประโยคชุดใหม่

หากคุณต้องการเรียกใช้ซอร์สโค้ดด้วยตัวเองอย่าลืมโหลด$src_textด้วยข้อความธรรมดาที่คุณเลือก

<html>
<head>
<title>Give Me Liberty Or Give Me Death</title>
<style>
body { margin:4em 6em; text-align:center; background-color:#feb; }
h1 { font-weight:normal; font-size:2em; margin-bottom:2em; }
blockquote { font-style:italic; }
</style>
</head>
<body>
<h1>A collection of quotes randomly generated from Patrick Henry's speech
<a href="http://www.gutenberg.org/ebooks/6">Give Me Liberty Or Give Me Death</a>
(and its accompanying Project Gutenberg blurb).</h1>
<?php

/* Give Me Liberty Or Give Me Death */
/* Plain text available from http://www.gutenberg.org/ebooks/6 */
$src_text = file_get_contents('libertyordeath.txt');

$bigrams = array();
$openers = array();
$loc = 0;
$new_sentence = true;
$last = false;
while (preg_match('/\'?\w+[^\s\[\]\*\(\)"#@]*/',$src_text,$matches,PREG_OFFSET_CAPTURE,$loc)) {
  $w = $matches[0][0];
  $loc = $matches[0][1]+strlen($w);
  $bareword = preg_replace('/\W/','',$w);
  if ($last) {
    if (!isset($bigrams[$last][$w])) $bigrams[$last][$w] = 1;
    else $bigrams[$last][$w]++;
  }
  if (!isset($bigrams[$bareword])) $bigrams[$bareword] = array();
  $last = $bareword;
  if ($new_sentence && preg_match('/^[A-Z]/',$w)) {
    if (!isset($openers[$w])) $openers[$w] = 1;
    else $openers[$w]++;
    $new_sentence = false;
  }
  if (ends_sentence($w)) {
    $new_sentence = true;
    $last = false;
  }
}

/* Now generate ten random sentences */

for ($ns=0; $ns<10; $ns++) {

  echo "<blockquote><p>";

  /* Choose a starting word */

  $sum = 0;
  foreach ($openers as $w=>$c) $sum += $c;
  $r = mt_rand(0,$sum);
  foreach ($openers as $w=>$c) {
    $r -= $c;
    if ($r<=0) break;
  }

  /* Barf out additional words until end of sentence reached */

  while(1) {
    echo "$w ";
    if (ends_sentence($w)) break;
    $bareword = preg_replace('/\W/','',$w);
    $sum = 0;
    foreach ($bigrams[$bareword] as $w=>$c) $sum += $c;
    $r = mt_rand(0,$sum);
    foreach ($bigrams[$bareword] as $w=>$c) {
      $r -= $c;
      if ($r<=0) break;
    }
  }

  echo "</p></blockquote>\n";
}

function ends_sentence($w) {
  if (!preg_match('/[\.\?!]$/',$w)) return false;
  if (preg_match('/^(\w|St|Mr|Ms|Mrs|Messrs|i\.e|e\.g|etc|Rd)\./i',$w)) return false;
  return true;
}

?>
</body>
</html>

+10 อันนี้ตอกย้ำจิตวิญญาณของความท้าทาย! ฉันไม่สามารถหาได้ในตอนนี้ แต่เคยเป็นเครื่องกำเนิดประโยคออนไลน์บน Google ที่ทำงานในลักษณะเดียวกัน แต่กราฟขนาดใหญ่ (หรือตัวเลือกที่ใหญ่กว่า n-gs) มาจากผลการค้นหาของ Google โดยการค้นหาคำและการสังเกต สิ่งที่ตามมาในตัวอย่างผลการค้นหา บางทีฉันจะสร้างมันขึ้นมาใหม่และโพสต์ไว้ที่นี่
Jason C

แล้วอันนี้ละ! "ท่านเราพบว่ามีความยินดีที่จะปรับปรุงการแข่งขัน" หรืออันนี้! "พวกเขาบอกเราถึงการคืนเงินในช่วงเวลาที่น่ากลัวเพื่อปรับปรุงส่วนของ Etext 6 วันที่อัปเดตล่าสุด: 5 พฤษภาคม 2005 เปิดตัวอย่างเป็นทางการสำหรับการต่อสู้ของเราคนเดียว"
Hosch250

1
But for me, death!: DI ต้องการสิทธิ์ใช้งาน / ข้อตกลงทั้งหมดสิ้นสุดลงอย่างยิ่ง
Navin

ฮ่าฮ่า "ปล่อยอย่างเป็นทางการสำหรับการต่อสู้ของเราคนเดียว"
Jason C

1
ฉันไม่ได้อะไรเลย." :(
TheNumberOne

29

หลาม

รายการนี้เลือกคำจากพจนานุกรมทั้งระบบ มันใช้ประโยชน์จากความจริงที่ว่าคุณสามารถทำให้คำนามเป็นคำกริยาและในทางกลับกันมากที่สุด ใช้การวิเคราะห์พฤติกรรมสองสามอย่างเพื่อจำแนกคำและหลีกเลี่ยงความเป็นไปไม่ได้

มันผลิตงบเกือบมีสติน้อย:

The snigger westernizes the bacteriologist.
A drizzle stoked the sentiments.

คนวิกลจริตหลายคน:

Tipper's orthopaedic knitwear plates a payroll.
A fibula teletypewritered a yogi.
The protozoan's spiralling skydive coats this veterinarian

และมีหลายสิ่งที่ฟังดูเหมือน Monty Python ทำให้เกิดความบ้าคลั่ง:

That rolling indictment tarries some bang's bulge.
Some inflammatory tush's intermarriage sextants some postman.
Some pentagon's manufacturer squeaked the wolverine.
A disagreeable participant is entertaining my optimized spoonful.

เวอร์ชัน 3 ได้รับการแก้ไขให้ใช้ไฟล์ข้อความใด ๆ เป็นอินพุต:

$ man python | python words.py
The disabled comma-separated source is using those wizards at exit.
$ cat COPYING | python words.py  #GPL
My user accord actions a gnu of software.
$ cat pg2591.txt | python words.py #Grimm's Fairy Tales 
Some bargain receives my threepence.
Any wrong worms your world.
$ cat words.py | python words.py #self reflection
Your filter_possesive not_nouned those prepositions.
$ ls /usr/bin | python words.py  #directory lists
Their dropbox funziped an arch.

รหัส(เวอร์ชั่น 3) :

import random
import string
import sys
import re

#words = open("/usr/share/dict/words").readlines()
words = re.sub("[]:;.,:?!<>{}()|=\"`[]",' ',sys.stdin.read(),flags=re.M).split()
words = list(set(words))

articles=('','a ','the ','some ','this ','that ','my ','any ','your ','their ',
             'all ','more '
             'an ') #an must be last
pl_articles=('','some ','those ','many ','the ','these ')
prepositions = ('of','by','to','for','from','in','with','on','which','when','at',
                     'into','as','if','near')
conjunctions = ('and','or','but')
verbs = ('is','are','was', 'be','do','came','been','had','have')
pronouns_s = ('he','she','it','we','you')
pronouns_o = ('him','her','them')

possesive=False
modifiers=0
use_prep = None

MAX_MODIFIERS=2

def is_modifier(w):
    return ("'" in w or
        w[-2:] in ('ry','ed','er','ic','al')  or
        w[-3:] in ('ing','est','ble','ous') or
        w[-4:] in ('less','ical','mmon') )

def is_verb(w):
    return (w in verbs or 
        w[-2:] in ('ed',) or
        w[-3:] in ('ing','ize') )

def is_article(w):
    return w+' ' in articles or w+' ' in pl_articles

def is_conjunction(w):
    return w in conjunctions

def filter_possesive(w,always=False): 
    global possesive
    #allow only one
    result = True if "'" in w else False
    if result:
        if always: return False
        if not possesive: 
            possesive = True
            return False
    return result

def is_preposition(w):
    global use_prep
    if w in prepositions:
        use_prep = w
        return True
    return False

def is_adverb(w):
    return w[-2:]=='ly'

def is_gerund(w):
    return w[-3:]=='ing'

def is_plural(w):
    return w[-1]=='s'

def not_verb(w):
    return (w in ('you','they','our','yes') or 
              w[-4:] in ('ness','such') or
              w in pronouns_o or w in pronouns_s
              )

def not_noun(w):
    return (w in verbs)


def getword():
    while True:
        w=words[random.randrange(len(words))].rstrip()
        if w[0] in string.ascii_uppercase: continue
        if is_article(w) or is_preposition(w):  continue
        if filter_possesive(w): continue 
        #print w
        return w

def get_article():
    return articles[random.randrange(len(articles)-1)]

#print '--s--'
substr=''
conjunction = False
while True:
    w=getword()
    if is_modifier(w):
        if modifiers < MAX_MODIFIERS:
            substr+=w+' '
            modifiers+=1
        else: continue
    elif is_adverb(w) or is_plural(w) or not_noun(w): continue
    else:
        if is_conjunction(w): 
            conjunction = w
            continue    
        substr= substr+w+' '
        if conjunction:
            substr+=conjunction+' '
            conjunction = False
            continue
        if w in pronouns_s: 
            substr = w+' '
            art=''
        else:
            art = get_article()
            if art is 'a ' and substr[0] in 'aeiou': art='an '
        substr= string.capwords(art+substr,'.')
        break

#print '--v--'
verbstr=''
while True:
    w=getword()
    if not_verb(w) or filter_possesive(w,True): continue
    elif is_adverb(w): verbstr+=w+' '
    elif is_gerund(w):
        verbstr+='is '+w+' '
        break
    elif is_verb(w):
        verbstr= verbstr+w+' '
        break
    elif is_modifier(w) or is_conjunction(w): continue
    else:
        if not is_plural(w):
            w=w+'ed' if w[-1]!='e' else w+'d'
        verbstr= verbstr+w+' '
        break

#print '--o--'
obstr=''
conjunction = False
while True:
    w=getword()
    if is_modifier(w):
        if modifiers<MAX_MODIFIERS:
            obstr+=w+' '
            modifiers+=1
        else: continue
    elif is_adverb(w) or not_noun(w) or w in pronouns_s: continue
    else:
        if is_conjunction(w): 
            conjunction = w
            continue
        obstr = obstr+w
        if conjunction:
            obstr+=' '+conjunction+' '
            conjunction = False
            continue
        if is_plural(w):
            art = pl_articles[random.randrange(len(pl_articles))] 
        else:
            art = articles[random.randrange(len(articles)-1)] 
            if art is 'a ' and obstr[0] in 'aeiou': art='an '
        if w in pronouns_o:
            obstr=w
        else:
            obstr= art+obstr
        break

#print '--p--'
while use_prep:
    w=getword()
    if (is_modifier(w) or is_preposition(w) or 
         is_gerund(w) or not_noun(w) or is_conjunction(w)):
        continue
    obstr+=' '+use_prep+' '+w
    use_prep=None

print substr+verbstr+obstr+'.'

3
ตัวอย่างประโยคทำให้ฉันหัวเราะอย่างหนักฉันกำลังร้องไห้! xD
mikhailcazi

cat FILE | COMMAND? UUOC ;)
nyuszika7h

ขอบคุณ @ nyuszika7h ฉันเรียนรู้บางอย่างวันนี้ ทำลายนิสัยที่คนแก่อาจจะยาก ...
ASHelly

1
This smoke toasted some nonresidents.. WOAH
phil294

25

ทุบตี

แรงบันดาลใจจากคำตอบ Matlab สมมติว่าคุณได้aptitudeติดตั้ง

r=$[ RANDOM % 7 ]
a=''
for i in `seq $r`; do a=$a'v'; done
if [ $r -ne 0 ]; then a='-'$a; fi
aptitude $a moo

เอาท์พุทที่เป็นไปได้ (ภาพจากนี้บทความวิกิพีเดีย)

ป้อนคำอธิบายรูปภาพที่นี่


7
ฉันไม่คิดว่า. /----\ -------/ \ / \ / | -----------------/ --------\ ----------------------------------------------เป็นประโยคที่ถูกต้อง
svick

1
@svick you winสามารถเป็นประโยคได้ (วัตถุ "อาร์กิวเมนต์" มีความหมายโดยนัย) และแม้ว่าจะไม่ใช่คำถามก็ไม่ได้ห้ามกรณีที่ผลลัพธ์ไม่ถูกต้อง
ace_HongKong การพึ่งพากัน

23

งูหลาม:

import random
l = ['Buffalo']
while random.randint(0,5) > 0:
    l.append('buffalo')
print ' '.join(l) + '.'

ตัวอย่าง:

  • ควายควาย
  • ควายกระบือควายควายควายควายควายควาย

น่าเสียดายที่มันมีการจัดการเครื่องหมายวรรคตอนและการใช้อักษรตัวพิมพ์ใหญ่ไม่ดี แต่ก็ไม่ได้ระบุว่าเป็นข้อกำหนด

นอกจากนี้นี่คือข้อมูลอ้างอิง


3
อย่าเพิ่มช่องว่างในตัวอักษรควาย ' '.join(l)แทนที่จะใช้ นั่นจะกำจัดพื้นที่ต่อท้าย จากนั้นคุณสามารถเพิ่มจุดต่อท้าย
Blacklight Shining

@ BlacklightShining อัปเดตแล้ว ขอบคุณสำหรับคำแนะนำ
8bittree

ไม่เป็นไร และ +1 สำหรับควาย :)
Blacklight Shining


1
แสดงด้วยitertools ,print " ".join(takewhile(lambda _: randint(0, 5), repeat("buffalo"))).capitalize() + "."
nmclean

16

สนิม + โทกิโปนะ

ภาษาใดเป็นที่ยอมรับดังนั้นฉันเขียนโปรแกรมในRustที่สร้างบางประโยคในภาษาโทคิโพนา

Toki Pona เป็นความพยายามในการสร้างภาษาที่เป็นธรรมชาติเพียงเล็กน้อยและมีไวยากรณ์ที่เรียบง่ายและธรรมดา นั่นเป็นคุณสมบัติที่มีประโยชน์มากสำหรับการประกวดครั้งนี้!

use std::rand;

#[deriving(Rand)]
struct Phrase { a: Option<~GNominal>, b: ~Sujet, c: ~Predicat }

#[deriving(Rand)]
enum Sujet { A(~GNominal), B(~SCompose) }

#[deriving(Rand)]
enum Predicat { C(~GVerbal), D(~PCompose) }

#[deriving(Rand)]
struct SCompose { a: ~Sujet, b: ~Sujet }

#[deriving(Rand)]
struct PCompose { a: ~Predicat, b: ~Predicat }

#[deriving(Rand)]
struct GNominal { a: ~nom::Nom, b: Multi<~adjectif::Adjectif> }

#[deriving(Rand)]
struct GVerbal { a: ~verbe::Verbe, b: Multi<~adjectif::Adjectif>, c: Multi<~ODirect> }

#[deriving(Rand)]
struct ODirect { a: ~GNominal}

#[deriving(Rand)]
enum Multi<T> { Zero, One(T), Two((T,T)) }

mod nom {
    #[deriving(Rand)]
    #[deriving(ToStr)]
    pub enum Nom {akesi,ala,ale,anpa,ante,ijo,ike,ilo,insa,jaki,jan,jo,kala,kalama,kama,kasi,ken,kili,kiwen,ko,kon,kule,kulupu,lape,lawa,len,lete,linja,lipu,luka,lupa,ma,mama,mani,meli,mi,mije,moku,moli,monsi,mun,musi,mute,nanpa,nasin,nena,nimi,noka,oko,olin,ona,pakala,pali,palisa,pana,pilin,pimeja,pini,pipi,poka,poki,pona,seli,selo,sewi,sijelo,sike,sina,sinpin,sitelen,sona,soweli,suli,suno,supa,suwi,tan,tawa,telo,tenpo,toki,tomo,tu,unpa,uta,utala,walo,wan,waso,wawa,weka,wile}
}

mod verbe {
    #[deriving(Rand)]
    #[deriving(ToStr)]
    pub enum Verbe {ante,awen,ijo,ike,jaki,jan,jo,kalama,kama,ken,kepeken,kule,kute,lape,lawa,lete,lili,lon,lukin,moku,moli,musi,mute,nasa,olin,open,pakala,pali,pana,pilin,pimeja,pini,pona,seli,sin,sitelen,sona,suli,suwi,tawa,telo,toki,tu,unpa,utala,wan,wawa,weka,wile,}
}

mod adjectif {
    #[deriving(Rand)]
    #[deriving(ToStr)]
    pub enum Adjectif {ala,ale,anpa,ante,awen,ike,insa,jaki,jan,jelo,kama,kin,kiwen,kon,kule,kute,kulupu,lape,laso,lawa,lete,lili,linja,loje,luka,lukin,mama,meli,mi,mije,moli,monsi,mun,musi,mute,nasa,ni,olin,ona,pali,pimeja,pini,poka,pona,sama,seli,sewi,sike,sin,sina,suli,suwi,taso,tawa,toki,tomo,unpa,uta,walo,wan,wawa,weka,wile,}
}

impl ToStr for Phrase {
    fn to_str(&self) -> ~str {
        self.a.as_ref().map_or(~"", |g| format!("{:s} la ", g.to_str()))
        + format!("{:s} li {:s}", self.b.to_str(), self.c.to_str())
    }
}

impl ToStr for Sujet {
    fn to_str(&self) -> ~str {
        match *self {
            A(ref v) => v.to_str(),
            B(ref v) => v.to_str(),
        }
    }
}

impl ToStr for Predicat {
    fn to_str(&self) -> ~str {
        match *self {
            C(ref v) => v.to_str(),
            D(ref v) => v.to_str(),
        }
    }
}

impl ToStr for SCompose {
    fn to_str(&self) -> ~str {
        format!("{:s} en {:s}", self.a.to_str(), self.b.to_str())
    }
}

impl ToStr for PCompose {
    fn to_str(&self) -> ~str {
        format!("{:s} li {:s}", self.a.to_str(), self.b.to_str())
    }
}

impl ToStr for GNominal {
    fn to_str(&self) -> ~str {
        format!("{:s} {:s}", self.a.to_str(), self.b.to_str())
    }
}

impl ToStr for GVerbal {
    fn to_str(&self) -> ~str {
        format!("{:s} {:s} {:s}", self.a.to_str(), self.b.to_str(), self.c.to_str())
    }
}

impl ToStr for ODirect {
    fn to_str(&self) -> ~str {
        format!("e {:s}", self.a.to_str())
    }
}

impl<T: ToStr> ToStr for Multi<~T> {
    fn to_str(&self) -> ~str {
        match *self {
            Zero => ~"",
            One(ref v) => v.to_str(),
            Two((ref v,ref w)) => format!("{:s} {:s}", v.to_str(), w.to_str()),
        }
    }
}

fn main() {
    let phrase = rand::random::<Phrase>();
    println!("{:s}\n{:?}", phrase.to_str(), phrase);
}

ฉันไม่พูด Toki Pona แต่ฉันพบว่าไวยากรณ์ของ Toki Pona เป็นชุดของกฎ BNFใน Wikipedia ฉันสร้างหนึ่ง struct หรือ enum สำหรับแต่ละกฎของ BNF และฉันใส่คำอธิบายประกอบไว้ด้วยderiving(Rand)ซึ่งทำให้ฉันมีวิธีสร้างโครงสร้างแบบสุ่มPhraseฟรี! จากนั้นฉันนำไปใช้ToStrสำหรับ structs เหล่านี้เพื่อแปลงเป็นสตริง

ฉันตั้งใจออกจากชื่อ struct เป็นภาษาฝรั่งเศสเพราะกฎ BNF ที่ฉันพบนั้นเป็นภาษาฝรั่งเศสและก็เพราะมันแสดงให้เห็นถึงลักษณะที่พูดได้หลายภาษาของการส่งของฉัน!

ตัวอย่างผลลัพธ์

บางคนเอาท์พุทและการแปลของพวกเขาว่าผมไม่อยู่บนพื้นฐานของกฎ BNFและพจนานุกรมภาษาโทคิโพนา ฉันแน่ใจว่าการแปลเหล่านี้ส่วนใหญ่ผิด แต่ Toki Pona ออกจากห้องไปมากสำหรับการตีความประโยค

nasin mi tawa la jan li jaki

ในขณะที่ฉันเดินทางมีคนปนเปื้อน

monsi li jaki li jan ike musi

ก้นสกปรกและเป็นคนเลวตลก

sina li tawa ale jelo e kili tawa e insa

คุณย้ายผลไม้และศูนย์กลางไปที่จักรวาลสีเหลือง

ประเด็น

  • ฉันไม่ตรวจสอบว่าคำกริยาเป็นสกรรมกริยาหรือไม่ดังนั้นประโยคบางประโยคไม่ถูกต้องตามหลักไวยากรณ์
  • structs บางตัวเกิดซ้ำและเมื่อกฎสามารถทำซ้ำได้ฉันสุ่มเลือกเอาท์พุทองค์ประกอบ 0, 1 หรือ 2 สิ่งนี้สามารถนำไปสู่การสร้างประโยคที่สร้างขึ้นมาอย่างยาวนานซึ่งมีคำหลายพันคำ ...
  • ฉันไม่สามารถตรวจสอบความถูกต้องของผลลัพธ์ได้จริง ๆ ฉันต้องพึ่งพาไวยากรณ์ BNF พจนานุกรมและการคาดเดาที่เป็นตัวของตัวเองทั้งหมด :)

1
sina li tawa ale jelo e kili tawa e insa == "คุณย้ายผลไม้และศูนย์กลางไปยังจักรวาลสีเหลือง" ค่อนข้างดีสำหรับเครื่องจักรซึ่งโดยปกติแล้วผู้ใช้ tp ขั้นสูงเท่านั้นที่สามารถใช้สิ่งก่อสร้างที่เปลี่ยนแปลงได้
MatthewMartin

1
monsi li jaki li jan ike musi == ก้น (ตูด? ใน jerk?) สกปรกและเป็นคนไม่ดีตลก
MatthewMartin

1
เฮ้ขอบคุณสำหรับความคิดเห็นของคุณ @MatthewMartin! แน่นอนฉันไม่ได้คาดหวังให้ผู้พูด Toki Pona ดูการส่งของฉัน แต่ฉันดีใจที่รู้ว่า senteces เหล่านี้ยังไม่สมบูรณ์ซึ่งพูดพล่อยๆ :)
barjak

คำแนะนำ: มันไม่ใช่รหัสกอล์ฟ
nyuszika7h

1
@ nyuszika7h ฉันไม่แน่ใจว่าจุดประสงค์ของความคิดเห็นของคุณคืออะไร แน่นอนมันไม่ใช่รหัสกอล์ฟเนื่องจากเป็นการประกวดความนิยม
barjak

14

หลาม

import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

7
คุณสามารถโต้แย้งที่import antigravityนำไปสู่ผลลัพธ์ได้I LEARNED IT LAST NIGHT! EVERYTHING IS SO SIMPLE!หรือไม่? : D
ace_HongKongIndependence

ไม่ต้องสงสัยใช่
Renae Lider

14

อารัมภบท

ใช้การย้อนรอยของอารัมภบทและไวยากรณ์เชิงกำเนิดโดยประมาณไวยากรณ์ภาษาอังกฤษเพื่อสร้างประโยคที่เป็นไปได้ทั้งหมด

รุ่นนี้มีโครงสร้างคำศัพท์และประโยคที่ค่อนข้าง จำกัด แต่ควรง่ายต่อการขยาย

รหัส:

% Define the vocabulary
verb(V) :- V = 'eats' | V = 'fights' | V = 'finds'.
subj_pronoun(P) :- P = 'he' | P = 'she' | P = 'it'.
obj_pronoun(P) :- P = 'him' | P = 'her' | P = 'it'.
name(N) :- N = 'alice' | N = 'bob'.
noun(N) :- N = 'cat' | N = 'door' | N = 'pen'.
article(H) :- H = 'the' | H = 'a'.

% Grammar
subject_phrase_short(H) :- subj_pronoun(H)
                         | name(H).
% Subordinate clause. Don't use verb_phrase here to avoid recursive clauses.
sub_clause([Which, Verb|T], Rest) :- Which = 'which', verb(Verb),
                                     object_noun_phrase_short(T, Rest).
subject_phrase([H|T], Rest) :- subject_phrase_short(H), Rest = T.
object_noun_phrase_short([A, N | T], Rest) :- article(A), noun(N), Rest = T
                                            | obj_pronoun(A), Rest = [N|T].
object_phrase(L, Rest) :- object_noun_phrase_short(L, Rest)
                        | object_noun_phrase_short(L, Rest1), sub_clause(Rest1, Rest).
verb_phrase([H|T], Rest) :- verb(H), object_phrase(T, Rest).
sentence(S) :- subject_phrase(S, Rest), verb_phrase(Rest, []).

เรียกใช้แบบสอบถามนี้:

sentence(L).

เพื่อสร้างประโยคที่เป็นไปได้ทั้งหมดในภาษานี้

ตัวอย่างผลลัพธ์บางส่วน:

L = [he, eats, the, cat] ;
L = [she, finds, a, door] ;
L = [alice, fights, the, door] ;
L = [he, fights, the, cat, which, eats, the, pen] ;
L = [alice, eats, him, which, finds, the, cat] ;

(แก้ไข: อนุญาตให้อนุประโยคของวัตถุ)


1
ตัวอย่างประโยคผลลัพธ์ใด?
TheDoctor

ใช่ฉันใส่ตัวอย่างไม่กี่คำตอบ มันสร้าง 2520 ผลรวมแม้ว่าดังนั้นฉันไม่สามารถโพสต์ได้ทั้งหมด ...
chrisd

11

หลาม

ในขณะที่คุณรู้ว่าคุณสามารถทำอะไรในหลามมีไม่กี่importวินาที ภารกิจง่ายๆนี้สามารถทำได้ด้วยสคริปต์ python 2 บรรทัดนี้

import random

print ("I like the number "+str(random.uniform(0,1)))

จำนวนประโยคที่สร้างโดยสคริปต์นี้มีขนาดใหญ่มาก: 10^12ประโยคที่แตกต่าง หากการอ่านตัวส่งข้อมูลใช้เวลาประมาณ 0.5 วินาทีจากนั้นการอ่านทั้งหมดจะใช้เวลานานกว่า 15,000 ปี!

ตัวอย่างประโยคบางส่วน:

  • I like the number 0.444371877853
  • I like the number 0.358614422548

แต่ประโยคที่สร้างขึ้นทั้งหมดมีเรื่องคำกริยาและวัตถุ

UPDATE:

ฉันได้รับการวิพากษ์วิจารณ์เกี่ยวกับคำศัพท์ที่ซับซ้อนซึ่งเครื่องมือที่ซับซ้อนนี้อาจสร้างขึ้นมา นี่คือรุ่นที่ยาวขึ้นเล็กน้อยซึ่งควรสอดคล้องกับคำศัพท์ส่วนใหญ่

import random

print ('I like the number'+''.join([' '+{'0':'zero','.':'point','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}[digit] for digit in str(random.uniform(0,1))])+'.')

นี่คือตัวอย่างประโยคบางส่วน:

  • I like the number zero point six three five nine zero eight one five eight four two four.
  • I like the number zero point four nine zero eight four four three two zero six two seven.

ฉันไม่พบคำบางคำในพจนานุกรมของฉัน
ดร. เบลิซาเรียส

5
ฉันปรับซอฟต์แวร์ของฉันให้พอดีกับพจนานุกรมที่น่าสงสารของคุณ
Antonio Ragagnin

2
ตกลง. ใน 15,000 ปีที่ผ่านมาฉันจะโพสต์เพื่อรับรองว่าฉันพบพวกเขาทั้งหมดแล้ว
ดร. เบลิซาเรียส

10

การเล่นกับพจนานุกรมภายใน Mathematica:

res = {};
SeedRandom[42 + 1];
Do[
  (While[
    If[(c = Flatten@WordData[RandomChoice[WordData[All]], "Examples"][[All, 2]]) != {},
     StringPosition[(c1 = RandomChoice@c), "'" | "-" | "\\" | "`"] != {}, True, True]];
   sp = ToLowerCase /@ StringSplit[c1, (WhitespaceCharacter .. | ",")];
   toChange = RandomSample[Range@#, RandomInteger[IntegerPart[{#/2, #}]]] &@Length@sp;
   If[StringPosition[ToString@WordData[sp[[#]], "Definitions"],  "WordData"] == {}, 
    sp[[#]] = RandomChoice@ WordData[All, RandomChoice@WordData[sp[[#]], "PartsOfSpeech"]]]
             & /@ toChange;
   AppendTo[res, StringJoin@Riffle[sp, " "]];)
  ,
  {10}];
res

คุณโชคดีพูด 70% ของเวลา มันสร้างสิ่งต่าง ๆ เช่น:

amygdaloid วงจรไฟฟ้า
โน่นสะตอเป็น unrestrictive แต่ขาด
สังคม longanimous เขา
ดุษฎีบัณฑิตการศึกษาการตอบกลับไม่ฉลาดให้อิสราเอล
กับจูเลียสซีซาร์ละครเพลงเล็ก ๆ น้อย ๆ
ไต่ไท
ตัดลงในศูนย์กีฬาต้านเจ้าคับแคบ
จำเป็นต้องใช้ผงซักฟอกภายนอก
ซองหมอผี necromantic
เหล่านี้กล้ามเนื้อ Vena ตรงข้าม latria เหมือง ถ้วยรางวัลภรรยานักลงทุนเทรนด์สีน้ำตาล
สิ่งที่ฟิลด์แบบพกพาของไฟ
umbra เสน่ห์คำตอบของฉัน
อีกเศษเศษหลวมสกรูพายุ scentless aslant เบน Aral ทะเลที่ซับซ้อนวาฟเฟิลที่ซับซ้อน
สำหรับความภาคภูมิใจของโลหะประเภทมองโกเลีย

แต่บางครั้ง:

การยอมรับของฉันในการต่อสู้อย่างน้อยที่สุดของ Lutzen จะดึงเงินเข้ามาในระหว่างที่ Hejira จากกลุ่ม
เหรียญทองเก้าเหรียญตัวเหลื่อมสกุล Seiurus ที่อบอุ่นใจผู้ชมของเธอ

โอ้การใช้ภาษาอังกฤษดีกว่าของฉัน


8

VBA / Excel

[แก้ไข 2]

ได้สอนวิธีการผันคำกริยาตัวอย่างด้านล่างเป็นคำง่าย ๆ ในอดีต:

โคเคนในระดับปานกลางเลื่อนตัวไปตามการตัดสินใจทันทีในประวัติศาสตร์ บทที่ปลอดภัยในระดับภูมิภาคได้สอดแทรกอยู่ภายในเอนทิตีสุ่มจำนวนมาก โดเมนด้านขวาสีเหลืองลบออกหลังเพศเปราะบางของสนามแม่เหล็ก มลภาวะทางร่างกายที่รุนแรงเริ่มต้นที่ความรู้สึกไม่ดีที่ตายไปแล้ว โรงละครแห่งปัญญาที่กล้าหาญไปที่ด้านหน้าของวรรณกรรมที่มีความรู้ที่เปราะบาง ผลลัพธ์ที่เกิดขึ้นจริงโดยทั่วไปจะต่อต้านออกไปจากไซต์ภูมิคุ้มกันที่ชื่นชอบ คู่เศรษฐกิจคงที่ได้รับการยอมรับจากความจำเป็นของมนุษย์ชั่วร้าย

รหัสที่เกี่ยวข้องดังต่อไปนี้ไม่รวมฟังก์ชันการแยกวิเคราะห์และการวนลูปที่น่าเบื่อ ส่วนหลักที่ขาดหายไปคือรายการคำต่าง ๆ (โดยส่วนของคำพูด) ซึ่งทำหลายฝ่าย, กาล, ผัน, ฯลฯ

คำทั้งหมดจะถูกสุ่มเลือก แต่ฉันบังคับให้จัดเรียงในรูปแบบประโยคเฉพาะ:

Debug.Print getWords("ad adj adj nns vpa1s pl ad adj adj nns")

... ซึ่งเป็นสิ่งที่ฉันใช้ในการสร้างผลลัพธ์ข้างต้น มันเป็นไปตามรูปแบบทั่วไปของ "สุนัขจิ้งจอกสีแดงรีบกระโดดข้ามสุนัขสีน้ำตาลขี้เกียจ"

Function getWords(strStruc As String) As String
    Dim i As Long
    Dim s As Long
    Dim strIn As String
    Dim strOut As String

    getWords = ""
    s = numElements(strStruc)
    For i = 1 To s
        strIn = parsePattern(strStruc, i)
        Select Case strIn
            Case ",", ";", ":", """" 'punctuation
                strOut = strIn
                getWords = Trim(getWords)
            Case "ai", "ad" 'indefinite article, definite article
                strOut = getArticle(strIn)
            Case "adj" 'adjective
                strOut = getWord("adj", 1)
            Case "nns" 'noun nominative singular
                strOut = getWord("n", 1)
            Case "nnp" 'noun nominative plural
                strOut = getWord("n", 2)
            Case "nps" 'noun posessive singular
                strOut = getWord("n", 3)
            Case "npp" 'noun posessive plural
                strOut = getWord("n", 4)
            Case "vpr1s" 'Present 1st Person Singular
                strOut = getWord("v", 1)
            Case "vpr2s" 'Present 2nd Person Singular
                strOut = getWord("v", 2)
            Case "vpr3s" 'Present 3rd Person Singular
                strOut = getWord("v", 3)
            Case "vi" 'Infinitive
                strOut = getWord("v", 4)
            Case "vpp" 'Present Participle
                strOut = getWord("v", 5)
            Case "vi" 'Imperative/Subjunctive
                strOut = getWord("v", 6)
            Case "vpa1s" 'Past Tense First Person
                strOut = getWord("v", 7)
            Case "vpa2s" 'Past Tense Second Person
                strOut = getWord("v", 8)
            Case "vpa3s" 'Past Tense Third Person
                strOut = getWord("v", 9)
            Case "vppr1s" 'Present Progressive First Person Singular
                strOut = getWord("v", 10)
            Case "vppr2s" 'Present Progressive Second Person Singular
                strOut = getWord("v", 11)
            Case "vppr3s" 'Present Progressive Third Person Singular
                strOut = getWord("v", 12)
            Case "vppe1s" 'Present Perfect First Person Singular
                strOut = getWord("v", 13)
            Case "vppe2s" 'Present Perfect Second Person Singular
                strOut = getWord("v", 14)
            Case "vpp3s" 'Present Perfect Third Person Singular
                strOut = getWord("v", 15)
            Case "vi1s" 'Imperfect First Person Singular
                strOut = getWord("v", 16)
            Case "vi2s" 'Imperfect Second Person Singular
                strOut = getWord("v", 17)
            Case "v13s" 'Imperfect Third Person Singular
                strOut = getWord("v", 18)
            Case "vsf" 'Simple Future
                strOut = getWord("v", 19)
            Case "vfp" 'Future Progressive
                strOut = getWord("v", 20)
            Case "vc" 'Conditional
                strOut = getWord("v", 21)
            Case "vcp" 'Conditional Perfect
                strOut = getWord("v", 22)
            Case "vci" 'Conditional Imperfect
                strOut = getWord("v", 23)
            Case "pl" 'location prepositions
                strOut = getWord("pl", 1)
        End Select
        getWords = getWords & strOut & " "
    Next i
End Function

[เริ่มโพสต์ต้นฉบับ]

ยังคงอยู่ในระหว่างดำเนินการจำเป็นต้องเพิ่มตรรกะสำหรับกาลและคำนามพหูพจน์คำนาม / คำกริยา:

การเดินทางโดยเฉลี่ยของคุณเราควรได้รับปริมาณหรืออุณหภูมิเพิ่มขึ้นกว่ามะเขือเทศของฉัน

... ซึ่งแยกวิเคราะห์ได้ แต่ไม่สมเหตุสมผลนัก

การเขียนโปรแกรมช่วยให้ชาวประมงที่สกปรกของพวกเขาไกลหมูของเราโยนแทนไม่มีประโยค

ขวา. ไม่ใช่ประโยคจริงๆ แต่ดีกว่าข้อความแสดงข้อผิดพลาด JavaScript

การอุทธรณ์ของเขายกคำถามทุกข้อที่ผู้หญิงของฉันเขียนไว้ข้างบนภาษาอังกฤษของเธอ

กิจวัตรการเสียดสีใกล้จะถึงจุดสูงสุดแล้ว ...

รหัสที่จะติดตามอานนท์ การประกวดครั้งนี้มีกำหนดสิ้นสุดหรือไม่?

[แก้ไข 1]

รหัสที่สร้างขึ้นด้านบน

Function getWord(sht As Worksheet) As String
    Dim i As Long
    Dim freq As Long
    Dim c As Long
    Dim f As Double
    Dim fSum As Double

    c = 4
    fSum = WorksheetFunction.Count(sht.Columns(c))
    f = Rnd() * fSum
    i = 2
    Do
        If i >= f Then Exit Do
        i = i + 1
    Loop
    getWord = sht.Cells(i, 1).Value
End Function
Function PCase(str As String) As String
    PCase = UCase(Left(str, 1)) & Right(str, Len(str) - 1)
End Function
Sub doMakeSentences01()
    Dim shtIn As Worksheet
    Dim shtOut As Worksheet
    Dim strSheet As String
    Dim rIn As Long
    Dim rOut As Long
    Dim cFreq As Long
    Dim c As Long
    Dim strPattern As String
    Dim w As Long
    Dim strOut As String
    Dim strIn As String
    Dim strWord As String

    cFreq = 4
    Set shtOut = Sheets("Output")
    rOut = shtOut.Range("A65536").End(xlUp).Row + 1

    strPattern = "anvajncanvian"
    For rOut = rOut To rOut + 1000
        strOut = ""
        For w = 1 To Len(strPattern)
            Set shtIn = Sheets(Mid(strPattern, w, 1))
            strWord = getWord(shtIn)
            If w = 1 Then strWord = PCase(strWord)
            strOut = strOut & strWord & " "
        Next w
        strOut = Trim(strOut) & "."
        shtOut.Cells(rOut, 1).Value = strOut
    Next rOut
End Sub

5
รหัสของคุณอยู่ที่ไหน
ace_HongKongIndependence

ดูการแก้ไขของฉันสำหรับรหัส
Brandon R. Gates

6

Perl 5

ตกลงความกล้าของโปรแกรมเป็นเพียงแค่นี้:

use v5.14;
my %pad = (
    ...
);
sub pad { shift =~ s(\{(.+?)\}){pad($pad{$1}[rand(@{$pad{$1}})])}rogue }
say ucfirst pad '{START}';

มันเป็นเครื่องยนต์ "madlib" ในการสร้างประโยคที่น่าสนใจคุณต้องเติม%padข้อมูลบางอย่าง นี่คือตัวอย่าง%pad...

my %pad = (
  START => ['{complex}.'],
  complex => [
    '{simple}',
    '{simple}, and {simple}',
    '{simple}, and {complex}',
    '{simple}, but {simple}',
    '{simple}, yet {simple}',
    'even though everybody knows {simple}, {simple}',
    'not only {simple}, but also {simple}',
  ],
  simple => [
    '{thing} {verb}s {thing}',
    '{thing} {verb}s {adverb}',
    '{thing} is {adjective}',
    '{things} {verb} {thing}',
    '{things} {verb} {adverb}',
    '{things} are {adjective}',
    '{thing} {past_verb} {thing}',
    '{things} {past_verb} {thing}',
  ],
  thing => [
    'the {adjective} gorilla',
    'the {adjective} mailbox',
    'Archbishop Desmond Tutu',
    'the beef salad sandwich',
    'the {adjective} stegosaur',
    'the summit of Mt Everest',
    'Chuck Norris',
    'the cast of television\'s "Glee"',
    'a {adjective} chocolate cake',
  ],
  things => [
    '{adjective} shoes',
    'spider webs',
    'millions of {adjective} eels',
    '{adjective} children',
    '{adjective} monkeys',
    '{things} and {things}',
    'the British crown jewels',
  ],
  verb => [
    'love',
    'hate',
    'eat',
    'drink',
    'follow',
    'worship',
    'respect',
    'reject',
    'welcome',
    'jump',
    'resemble',
    'grow',
    'encourage',
    'capture',
    'fascinate',
  ],
  past_verb => [  # too irregular to derive from {verb}
    'loved',
    'ate',
    'followed',
    'worshipped',
    'welcomed',
    'jumped',
    'made love to',
    'melted',
  ],
  adverb => [
    'greedily',
    'punctually',
    'noisily',
    'gladly',
    'regularly',
  ],
  adjective => [
    'enormous',
    'tiny',
    'haunted',
    'ghostly',
    'sparkling',
    'highly-decorated',
    'foul-smelling',
    '{adjective} (yet {adjective})',
    'expensive',
    'yellow',
    'green',
    'lilac',
    'tall',
    'short',
  ],
);

นี่คือตัวอย่างบางส่วนของภูมิปัญญาที่ฉันค้นพบจากสิ่ง%padนั้น ประโยคเหล่านี้ยังไม่ได้รับการแก้ไขสำหรับความยาวเครื่องหมายวรรคตอนไวยากรณ์ ฯลฯ แม้ว่าฉันได้คัดบางส่วนที่ไม่น่าสนใจและจัดเรียงลำดับที่ประโยคปรากฏ - พวกเขาไม่ได้อยู่ในลำดับที่พวกเขาสร้างขึ้น แต่ฉันพยายามที่จะ ใช้พวกเขาเพื่อเล่าเรื่อง: เรื่องราวที่ฉันหวังว่าคุณจะพบได้ทั้งการสัมผัสและการกระตุ้นความคิด

  • ใยแมงมุมสั้น
  • ใยแมงมุมติดใจเป็นประจำ
  • ลิงสั้นเป็นประกาย แต่ใยแมงมุมดื่มอย่างตะกละตะกลาม
  • ลิงที่ส่องแสง (แต่มีกลิ่นเหม็น) ตามลิงกอริลลาตัวเล็ก ๆ
  • ยอดเขาเอเวอเรสต์ยินดีต้อนรับสเตโกซอร์ที่ตกแต่งอย่างดี
  • ไม่เพียง แต่การประชุมสุดยอดของยอดเขาเอเวอร์เรสท์เท่านั้นยังมีราคาแพง แต่ยังมีนักแสดงจากโทรทัศน์“ Glee” ที่ตามด้วยกอริลลาที่เปล่งประกาย
  • นักแสดงทางโทรทัศน์ "Glee" คล้ายกับกล่องจดหมายไลแลค
  • ตู้ไปรษณีย์ราคาแพงนั้นสูงและเตโกซอร์ราคาแพงกระโดด Chuck Norris รองเท้าสีเขียวกระโดดแซนวิชสลัดเนื้อ
  • แซนวิชสลัดเนื้อชอบ Chuck Norris
  • ปลาไหลเป็นล้านเป็นสีเขียว (ยังน่ากลัว)

ตอนนี้ถ้าคุณสามารถเติมแผ่นโดยใช้โปรแกรม
Pureferret

การเติมแผ่นโดยทางโปรแกรมไม่ใช่เรื่องท้าทาย เพียงแค่ขูดวิกิชันนารีหรืออะไรซักอย่าง ที่ไม่ยอมให้ประโยคสนุกเช่นนั้น
tobyink

มันไม่ใช่ความท้าทายมากนัก แต่ฉันคิดว่ามันเป็นส่วนที่สนุกของมัน
Pureferret

5

Ms Word

ฉันไม่แน่ใจว่านี่เป็นสิ่งที่ยอมรับได้หรือไม่ แต่เนื่องจาก html นั้นคือฉันคิดว่าสิ่งนี้ก็ควรจะยอมรับเช่นกัน

 =rand(1,1)

ตัวอย่างประโยค:

บนแท็บแทรกแกลเลอรีมีรายการที่ออกแบบมาเพื่อประสานงานกับลักษณะโดยรวมของเอกสารของคุณ

คุณสามารถใช้แกลเลอรีเหล่านี้เพื่อแทรกตารางส่วนหัวส่วนท้ายรายการหน้าปกและเอกสารก่อสร้างเอกสารอื่น ๆ

คุณสามารถระบุจำนวนประโยคและย่อหน้าได้


4

กำลังดำเนินการโดยใช้JSoupและsimpleNLG

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import simplenlg.framework.NLGFactory;
import simplenlg.lexicon.Lexicon;
import simplenlg.phrasespec.SPhraseSpec;
import simplenlg.realiser.english.Realiser;

/**
 * Scapes words from Wiktionary then assembles them into sentences
 * 
 * @author pureferret
 *
 */
public class SentenceBuilder {
    static ArrayList<String> ListOfWordTypes= new ArrayList<>(Arrays.asList("Noun","Verb","Adjective","Adverb","Proper noun","Conjunction"));
    private static String RandomWiktWord ="http://toolserver.org/~hippietrail/randompage.fcgi?langname=English";  
    /**
     * @param args
     */
    public static void main(String[] args) {
        Lexicon lexicon = Lexicon.getDefaultLexicon();
        NLGFactory nlgFactory = new NLGFactory(lexicon);
        Realiser realiser = new Realiser(lexicon);

        ArrayList<String> nounList = new ArrayList<String>();
        ArrayList<String> verbList = new ArrayList<String>();
        ArrayList<String> adjeList = new ArrayList<String>();
        ArrayList<String> adveList = new ArrayList<String>();
        ArrayList<String> pnouList = new ArrayList<String>();
        ArrayList<String> conjList = new ArrayList<String>();


        String word= null;
        String wordType = null;

        try {
            newDoc:
            while( nounList.size()<1 ||
                    verbList.size()<1 ||
//                  adjeList.size()<2 ||
//                  adveList.size()<2 ||
                    pnouList.size()<1){
                Document doc = Jsoup.connect(RandomWiktWord).get();
                Element bodyElem = doc.body();
                word = bodyElem.select("h1>span[dir=auto]").get(0).ownText();
                int wtIdx = 0;
                while(wtIdx<bodyElem.select("div#mw-content-text span.mw-headline").size()){
                    wordType = bodyElem.select("div#mw-content-text span.mw-headline").get(wtIdx).id()
                            .replace("_", " ");
                    wtIdx++;
                    switch (wordType) {
                    case "Proper noun":
                        pnouList.add(word);
                        continue newDoc;
                    case "Noun":
                        nounList.add(word);
                        continue newDoc;
                    case "Verb":
                        verbList.add(word);
                        continue newDoc;
                    case "Adjective":
                        adjeList.add(word);
                        continue newDoc;
                    case "Adverb":
                        adveList.add(word);
                        continue newDoc;
                    case "Conjunction":
                        conjList .add(word);
                        continue newDoc;
                    default:
                        break;
                    }
                }
            }
                SPhraseSpec p = nlgFactory.createClause();
                p.setSubject(pnouList.get(0));
                p.setVerb(verbList.get(0));
                p.setObject(nounList.get(0));

                String output2 = realiser.realiseSentence(p); // Realiser created earlier.
                System.out.println(output2);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.err.println(word + " is a " + wordType);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            System.err.println(word + " is a " + wordType);
        }
    }

}

ปัญหาที่พบ:

  • ประโยคนั้นง่ายเกินไป
  • เป็นครั้งคราว 404 วินาที (ไม่มีการจัดการที่ดี!)
  • สร้างได้ครั้งละหนึ่งประโยคเท่านั้น
  • ใช้ตัวเรือนสวิตช์!

ตัวอย่างผลลัพธ์:

Popoloca prickethes runner runner ถั่ว
Tropic of Capricorn รับลำแสงเพิ่มขึ้น
ปักกิ่งพ้องหมอนกล่อง
Chukchis enculturateds ที่มีอิทธิพล


3

PHP

<?php
  $trends = file_get_contents('http://www.google.com/trends/hottrends/widget?pn=p1&tn=30');
  preg_match_all("/widget-title-in-list'>(.+?)</", $trends, $m);

  $q = urlencode($m[1][array_rand($m[1])]);
  $page = file_get_contents("http://www.google.com/search?q=$q&btnI=1");
  preg_match_all('/[A-Z]([\w,]+ ){2,}[\w, ]+?[.!]/', strip_tags($page), $m);

  echo $m[0][array_rand($m[0])];

สิ่งนี้ดึงการค้นหา google ที่ได้รับความนิยมสูงสุด 30 รายการทำการค้นหา "I Feel Lucky" จากนั้นแสดงประโยคสุ่มจากหน้านั้นด้วยคำอย่างน้อย 3 คำ

ตัวอย่าง:

"เธอถูกมองว่าเป็นเหรียญที่โปรดปรานในเหตุการณ์"

"เคทจบการศึกษาจากโรงเรียนมัธยมปลายเมื่อต้นปี"

"15 เมษายน 2014 เพื่อส่งเสริมการปฏิบัติตามนโยบายชีวประวัติของผู้คนที่มีชีวิต"

"ในนามของไบรอันเราครอบครัวของเขาขอขอบคุณทุกคนที่ได้แสดงความรักการสวดมนต์และการสนับสนุน"

"บทความนี้เกี่ยวกับนักอเมริกันบาสเก็ตบอล"

"ขออภัยเบราว์เซอร์ของคุณปิดใช้งาน JavaScript หรือไม่มีผู้เล่นที่รองรับ"


3

Python 2.7

python2.7 -c "import urllib2, pprint; pprint.pprint([str(x[:x.find('<')]) for x in unicode(urllib2.urlopen('http://codegolf.stackexchange.com/questions/21571/generate-an-understandable-sentence').read(), 'utf8').split('<p>') if x.find('<') >= 1][1].split('.')[0])"

เอาท์พุท:

สร้างประโยคที่สามารถอ่านและเข้าใจได้


ใช้ URIs ที่ใช้ร่วมกันของ Stack Exchange (เช่น/q/21571แทน/questions/21571/generate-an-understandable-sentence)
Blacklight Shining

2
เนื่องจากนี่ไม่ใช่โค้ดกอล์ฟการแบ่งบรรทัดสำหรับการอ่านจึงน่าจะดี
nyuszika7h

2

การเขียนสคริปต์เชลล์

สคริปต์นี้จะแสดงชื่อของคำถามแรกที่อยู่ด้านบนสุดของไซต์นี้เสมอ ข้อสันนิษฐานของฉันคือชื่อคำถามที่มนุษย์อ่านได้เสมอ และมันจะเปลี่ยนแบบไดนามิก ดังนั้นเมื่อมีคำถามใหม่เกิดขึ้นและเมื่อสคริปต์ถูกเรียกใช้งานคำถามนั้นจะให้ชื่อคำถามล่าสุด

curl "codegolf.stackexchange.com" -s |  w3m -dump -T text/html > foo.txt
awk 'f;/more tags/{f=1}' foo.txt > foo1.txt
sed '8q;d' foo1.txt

ทดลอง 1 เอาท์พุท

Find words containing every vowel

ทดลอง 2 เอาท์พุท

Hello World 0.0!

แก้ไข

ไม่ได้ใช้ไฟล์ใด ๆ หากไม่มีไฟล์ฉันสามารถใช้สคริปต์ด้านล่าง

value1=$(curl "codegolf.stackexchange.com" -s |  w3m -dump -T text/html)
echo "$value1" | grep -A 8 "more tags" | tail -1

เอาท์พุต

Generate an understandable sentence

1
ไม่เป็นอ่านพวกเขาโดยตรงจากไฟล์ ...
rafaelcastrocouto

ฉันได้ทำการเปลี่ยนแปลงที่จะไม่ใช้ไฟล์ ตอนนี้มันเพิ่งใช้ตัวแปร แล้วอันนี้ละ?
Ramesh

2
ลบการลงคะแนน!
rafaelcastrocouto

2

JavaScript (ES6)

var t='';for(f of [_=>foo,_=>null.a,_=>0..toString(0)])try{f()}catch(e){t+=e.message+'\n';}t

ทำงานในคอนโซลผลิต

foo is not defined
null has no properties
radix must be an integer at least 2 and no greater than 36

สั้นกว่านี้:t='';for(f of [_=>foo,_=>null.a,_=>0..toString(0)])try{f()}catch(e){t+=e.message+'\n'}t
แปรงสีฟัน

2

อีกหนึ่งสคริปต์ Python

คำตอบของ user3058846ไม่ได้เลวร้าย แต่มันแสดงทุกประโยคทุกครั้ง ที่นี่ฉันเสนอสคริปต์ที่สร้างประโยคสุ่มจากZen of Python :

from random import choice
import subprocess
proc = subprocess.Popen(('python', '-c', 'import this'), stdout=subprocess.PIPE,)
# Get output of proc, split by newline
sentences = [x for x in proc.communicate()[0].splitlines() if x != '']
print(choice(sentences))

ในบรรทัดเดียวสำหรับแฟน :

from random import choice;import subprocess;print(choice([x for x in subprocess.Popen("python -c 'import this'",shell=True,stdout=subprocess.PIPE).communicate()[0].split('\n') if x]))

(Boooh สกปรก)

ตัวอย่าง:

>>> a()  # <--- a is just the oneline above
Explicit is better than implicit.
>>> a() 
Although never is often better than *right* now.
>>> a() 
Errors should never pass silently.
>>> a() 
Special cases aren't special enough to break the rules.


อีกวิธีที่สนุกใน Python

ต้องขอบคุณ @TheDoctor ที่ทำให้แนวคิดนี้เป็นจริง :-) ปิดเสียงการนำเข้าให้เงียบแล้วเล่นกับท่วงท่าเข้ารหัสที่เข้ารหัสในโมดูล

import sys, random 
_stdout, sys.stdout = sys.stdout, open('/tmp/trash', 'w')  # silent the stdout just for the import
import this
sys.stdout = _stdout
lst = []
for x in this.s:
    if x in this.d:
        lst.append(this.d[x])
    else:
        lst.append(x)

# Then, example from the interpreter
>>> random.choice(''.join(lst).split('\n'))
'Beautiful is better than ugly.'
>>> random.choice(''.join(lst).split('\n'))
'Although never is often better than *right* now.'
>>>

โดยทั่วไปแล้วการใช้งานshell=Trueไม่ดี subprocess.Popen(('python', '-c', 'import this'))แม้ว่าจะไม่ปลอดภัยในกรณีนี้ที่คุณไม่ได้นำเข้าของผู้ใช้ผมจะเลือกใช้
nyuszika7h

คุณรู้หรือไม่ว่าคุณสามารถเงียบบทกวีได้import thisมีตัวแปรในโมดูลthisที่มีข้อความทั้งหมด แต่เข้ารหัส นอกจากนี้ยังมีพจนานุกรมในการถอดรหัส
TheDoctor

1
@TheDoctor ดูคำตอบที่อัปเดตของฉัน: D
Maxime Lorant

1

Python 3

รับประกันว่าจะสร้างผลลัพธ์ทางไวยากรณ์! (ปกติ.)

import re
from urllib.request import urlopen
from random import random, choice as pick

letters = "abcdefghijklmnopqrstuvwxyz"
wordregex = re.compile(r'a href="/wiki/([a-z_]+)"')
subjects = {1:("I","we"), 2:("you",), 3:("they",)}
objects = {1:("me","us"), 2:("you",), 3:("him","her","it","them")}
patterns = ["{0} {1} {2}.",
            "Why do {0} {1} {2}?",
            "It's because {0} {1} {2}, of course.",
            "Did {0} {1} {2}?",
            "{0} will not {1} {2}!",
            ]

wiktionaryurl = "http://en.wiktionary.org/w/index.php?" + \
              "title=Category:English_{0}&pagefrom={1}"

def getWord(category):
    subset = pick(letters) + pick(letters)
    url = wiktionaryurl.format(category, subset)
    try:
        response = urlopen(url)
    except:
        print("An error occurred while connecting to the Internet!")
        return "fail"
    page = str(response.read())
    word = pick(wordregex.findall(page))
    word = word.replace("_", " ")
    return word

for i in range(10):
    verb = getWord("transitive_verbs")
    subjPerson = pick([1,2,3])
    subj = pick(subjects[subjPerson])
    if random() > 0.4:
        # Use a plural noun for the object
        obj = getWord("plurals")
    else:
        # Use a pronoun for the object
        objPerson = pick([1,2,3])
        while subjPerson == objPerson and subjPerson in (1,2):
            objPerson = pick([1,2,3])
        obj = pick(objects[objPerson])
    sentence = pick(patterns).format(subj, verb, obj)
    sentence = sentence[0].upper() + sentence[1:]
    print(sentence)

wordregexที่จะทำให้มันสมบูรณ์แบบไวยากรณ์ลบขีดล่างจาก การทำเช่นนี้จะไม่อนุญาตให้ใส่คำหลายคำที่นำไปสู่ประโยคที่ไม่ดีเช่น "เราซิปคุณได้

วิ่งตัวอย่าง:

We appropriate journals.
I will not masticate you!
Did you lower me?
Why do I sag estoppels?
They will not proofread you!
It's because you unbeguile mucosae, of course.
Why do I flack zakuski?
You will not visit junkpiles!
Did they goat us?
Why do we prefix nolids?

ผลลัพธ์ที่โปรดปราน:

They you her.

ดูมันขึ้น: http://en.wiktionary.org/wiki/you#Verb


0

หลาม

ผลลัพธ์:

$ python mksentence.py
infringement lecture attainment
Produce more? (Y/N)y
impeachment recoup ornament
Produce more? (Y/N)y
maladjustment edit discouragement
Produce more? (Y/N)y
embellishment guest punishment
Produce more? (Y/N)y
settlement section escapement
Produce more? (Y/N)y
segment withhold recruitment
Produce more? (Y/N)

ฉันใช้รายการคำศัพท์จากที่นี่ค้นหาคำที่มีสระทุกสระ

สามารถเพิ่มกฎเพิ่มเติมได้ ตัวอย่างเช่นหากคำที่ลงท้ายด้วย "ness" และคำนั้นอยู่ในชุดโดยไม่มีคำต่อท้ายแสดงว่าเป็นคำนาม

รหัสแหล่งที่มา:

#!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sw=4 tw=72 :

from __future__ import (unicode_literals, absolute_import,
                        division, print_function)

import random                     

if __name__ == "__main__":        
    filename = 'corncob_lowercase.txt'
    noun = set()
    verb = set()
    whole_words_set = {word.rstrip() for word in open(filename)}

    for word in whole_words_set:
        if word.endswith('ment'):
            noun.add(word)
        elif word.endswith('ing'):
            if word[:-3] in whole_words_set:
                verb.add(word[:-3])
            elif word[:-3]+"e" in whole_words_set:
                verb.add(word[:-3]+"e")
    noun_list = list(noun)
    verb_list = list(verb)
    while True:                   
        sentence = "%s %s %s" % (random.choice(noun_list),
                                 random.choice(verb_list),
                                 random.choice(noun_list))                                                                                           
        print(sentence)
        if input("Produce more? (Y/N)").lower() == "n":
            break

3
ฉันดูดที่ Python และภาษาอังกฤษจริง ๆ หรือคุณเอาท์พุท 3 คำนามแทน 2 คำนามและคำกริยา?
ace_HongKongIndependence

@ โอ๊ะโอฉันตัดสินใจแก้ไขรหัสในนาทีสุดท้าย :-(
yegle

0

ทุบตี

พยายามที่จะเรียกใช้โปรแกรมที่มีอยู่ แต่ไม่ได้ติดตั้งให้ (ใน Linux Mint 13)

$ say
The program 'say' is currently not installed.  To run 'say' please ask your administrator to install the package 'gnustep-gui-runtime'

ในความแตกต่างที่แตกต่างกันมันให้ประโยคที่แตกต่าง
TheDoctor

นั่นเป็นเหตุผลที่ฉันพูดใน LM13
user80551

0

Python 3

ใช้เวลาอีกที่เซนของงูใหญ่แรงบันดาลใจจากคำตอบของ Maxime

import codecs
import os
import sys
import random

stdout = sys.stdout
sys.stdout = open(os.devnull, 'r+')

import this

sys.stdout.close()
sys.stdout = stdout

zen = codecs.decode(this.s, 'rot-13').splitlines()

print(random.choice(zen))

0
var vocab={
    noun:{
        tp:{
            singular:["Mike","Chan","Karl","Mithun","Debasish","Kamal","Group","Crowd","He","She"],
            plural:["They"],
        },
        fp:{
            singular:["I"],
            plural:["We"]
        },
        sp:{
            singular:["You"],
            plural:["You"]
        }

    },
    verbIndicator:{
        tp:{
            present:{
                singular:["is"],
                plural:["are"]
            },
            past:{
                singular:["was"],
                plural:["were"]
            }
        },
        fp:{
            present:{
                singular:["am"],
                plural:["are"]
            },
            past:{
                singular:["was"],
                plural:["were"]
            }
        },
        sp:{
            present:{
                singular:["are"],
                plural:["are"]
            },
            past:{
                singular:["were"],
                plural:["were"]
            }
        }
    },
    verb:{
        continuous:{
            consumer:["having"],
            performer:["doing","playing","watching"]
        },
        simple:{
            consumer:["had"],
            performer:["did","played","watched"]
        }
    },
    dependentAction:{
        consumer:["food","fun","badtime"],
        performer:["movie","cricket","song","dance"]
    },
    independentAction:["Cooking","Playing","singing"],
    adjective:["good","bad","excellent","awesome"],
    object:["boy","Person","girl","Human being","Man","Mental"]
}

var referenceBook={
    figure:["fp","sp","tp"],
    time:["present","past"],
    singularity:["singular","plural"],
    verState:{
        present:["continuous"],
        past:["continuous","simple"]
    },
    objectRole:["consumer","performer"]
};

function getTerm(term) {
    var cur = referenceBook[term] || [];
    var randomIndex = Math.ceil((Math.random() * 93967)) % cur.length;
    return cur[randomIndex]

}
function getToken(key) {
    var path = key.split("-");
    var token = vocab;
    path.forEach(function(s) {
        token = token[s];
   });

    return token[Math.ceil((Math.random() * 1000)) % token.length];

}

function generateSentence(rules) {
    rules.forEach(function(str) {
        var m = str.match(/{[^}]*}/g)

        var variable = {};
        if (m) {
            m.forEach(function(s) {
                s = s.replace(/(^{)|(}$)/g, "");
                variable[s] = getTerm(s);
            });

            for (var each in variable) {
                str = str.replace(new RegExp("{" + each + "}", 'g'), variable[each]);

            }
        }
        var cur = str.split("|");
        var sentence = "";
        cur.forEach(function(s) {
            sentence += " " + getToken(s);

        })
        console.log(sentence);

    })


};
/*

In the rules array, I specify rules for the sentence to be genrated

*/

var rules = [
    "noun-{figure}-{singularity}|verbIndicator-{figure}-{time}-{singularity}|verb-continuous-{objectRole}|dependentAction-{objectRole}", 
    "noun-sp-singular|adjective|object"
];

generateSentence(rules);

4
โปรดระบุภาษานี้
Rodolfo Dias

1
@RodolfoDias ฉันค่อนข้างแน่ใจว่านี่คือ Javascript ... ไม่แน่ใจว่า
TheDoctor
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.