text:
Fun with Matching Braces
The contest is to make a program or function that takes an arbitrary string
resembling source code and checks to see if the "braces" follow the basic rules for
brace matching. That is, the number of left braces and right braces have to match, and you
can't have a right brace without a corresponding prior left brace.
You may choose to use any "brace" among ( [ { <
Your program must output/return a true-y value or 'Y' if the input is legal and a false-y value or 'N' if the input is illegal.
Scoring
Your score is the number of bytes in your source minus bonuses.
Bonuses

-20 per each additional brace type handled among ( [ { <
-30 if you handle multiple brace types and don't allow mismatched braces like <(>)
-50 points if you handle /* */ or // comments (the same way C or Java does)
-20 points if you handle both types of comments
-50 if you ignore braces inside ' and " quotes. To get the points you also have to check that quotes properly match. Eg: ("')"') is not a valid "program" but ("')") is. You do not have to worry about escaped characters. "\"" is an illegal program if you go for this bonus.

So if your program is 327 ASCII characters long, handles ( and [, doesn't check mismatching, and handles // comments and quotes, you get:
327 - 20 * 1 - 0 - 50 - 0 - 50 = 207 points
EDIT: Added bonuses for ignoring braces inside ' and " quotes
EDIT 2: Return values cannot be any string. Must be true/false 1/0 'Y'/'N' ect.
EDIT 3: Since there is some confusion, here is some pseudo-BNF to give an idea of what is expected.
Grammar for minimal program:
exprs = expr exprs
expr = ( exprs ) || not_braces* || nil
Grammar for all bonuses:
exprs = expr exprs
expr = ( exprs ) || [ exprs ] || { exprs } || < exprs > || // not_newline* \n || /* not_end_comment* */ || not_braces* || nil
Note that if you do the bonuses, you will both accept and reject things that the basic program would not.

How should we handle braces in string literals, like "Hel(o"? I assume they should be handled like your -50 for comments, but you don't specify that.

@Danny Ugh, I should have known I'd forget something. Sure, let's add that.

Stack based languages may be particularly good at this

your grammars look good, but the first paragraph makes it sound like [(]) is valid

@Sparr The first paragraph only applies to a program without bonuses, in which case your example is valid. Your program only needs to reject that example if you want the bonus -30.

@ThomasKwa Encouraging the coders to handle comments and strings makes the two challenges very different, IMO.

Perl, (136 130 129 chars - (20*3) - 30 - 50 - 20 - 50) == -81
<3 recursive REs.
$/=$_;print!(<>!~m#^(([^][<{('"/)}>]|'[^']*'|"[^"]*"|/((?![*/])|\*((?!\*/).)*\*/|/[^\n]*+)|<(?1)>|\((?1)\)|\[(?1)]|{(?1)})*)$#s)

You can shorten this by clearing $/ to avoid joining, by changing <STDIN> to <> (which reads from STDIN unless a file name is passed on the command line), and by outputting an empty string (which should count as false-y) in the output if the match fails: to $/=$_;$_=<>;print!!m#...#.

Congratulations

PHP, -4 (156 - 20*3 - 30 - 50 - 20)
<?php $x=preg_replace("!(//.*|/\*.*\*/|[^()[\]{}<>])!sm",'',$argv[1]);while(strlen($x)!=strlen($x=str_replace(str_split('()[]{}<>',2),'',$x)));print $x?0:1;

It removes comments
It filters out all characters different than (, ), [, ], {, }, <, >
It replaces all (), [], {}, <> pairs until there are no matches
Prints 1 if the string is empty, 0 otherwise

(Edit: changed the regex; the source code is now 156 instead of 175)

GolfScript, 38 chars − 3 × 20 − 30 = −52 points
0\{")]>}([<{"?.4/"4^^{0}*

;"n/=~}/;]!

Prints 1 if all the braces in the input are correctly balanced, 0 otherwise.
Bonus points for:

handling all four types of braces: 3 × 20 points
not allowing mismatched braces: 30 points

This solution uses the GolfScript internal stack to keep track of which braces have been seen so far.  When an opening brace is encountered, it is pushed onto the stack; when a closing brace is encountered, the code checks if there's a matching opening brace on the stack.  If there is, it is popped off; otherwise a sentinel value (0) matching no brace is push onto the stack, ensuring that it cannot ever be popped off.
One such sentinel value is pushed onto the stack at the beginning, to guard against stack underflow if there are too many closing braces.  At the end, the program simply checks whether the stack is empty except for the initial sentinel value.

Lua - 51
print(not not("("..io.read"*a"..")"):match"^%b()$")

What this program is doing, is wrapping the input string in (), then it matches it against a pattern (not a regex). The pattern matches beginning of string followed by string containing balanced parentheses, followed by end of string.
On a successful match, the whole string is returned, which is turned into true by not not. If match is unsuccessful, nil is returned, which turns info false because of not not.

Don't forget to add your explanation.

@Quincunx done (comment too short)

C, 70 62 61
A;main(c){for(;~c&~A;c=getchar())A-=c==41,A+=c==40;exit(!A);}

Alternatively, supporting all bracket types: 147 - (3*20) = 87
A,B,C,D;main(c){for(;~(c=getchar())&~A&~B&~C&~D;)c-40?c-41?c-91?c-93?c-'{'?c-'}'?c-60?c-62||D--:D++:C--:C++:B--:B++:A--:A++;puts(A|B|C|D?"N":"Y");}

The program reads in a single character at a time.  Every time a ( is found a counter is incremented.  Similarly, every time a ')' is found a counter is decremented.  If the counter ever drops below 0, we know a ) was found without a prior (.  When we reach EOF, if the counter equals 0, we have success!
EDIT: A big thanks to @ugoren!

~c&~A is great. But c=~getchar() can save parentheses (but requires some changes, I think it can help). A-=c==41 can save one.

Thanks!  A-=c==41 really helped reduce the character count.  I'll play around a bit, but getting rid of the parens really kills the evaluation order...not sure how to get around that right now.

GolfScript 37
{[40.)]&},.,,\`{\>}+%{0\~}%(!\{0<},!&

Suppose the input to the program is '(123(abc)(hello))'.  First, filter out all characters that are not ( (ASCII 40) or ) (ASCII 41):
{[40.)]&},  #Stack is now '(()())'

Next, generate an array from 0 to the length of the array:
.,, #Stack is now '(()())' [0, 1, 2, 3, 4, 5]

Now, generate all suffixes of the filtered string
\`{\>}+% #Stack is now ['(()())', '()())', ')())', '())', '))', ')' ]

Recall that in GolfScript, ( decrements integers and ) increments them.
So, checking if the parentheses are valid is equivalent to checking if that no suffix, when treated as a code block and applied to 0, dips below 0 (so that there are more close braces than open braces) and that the whole string, when treated as a code block and applied to 0, return 0 (so that there is an equal number of open and close parenthesis).
So, apply each suffix to 0:
{0\~}% #Stack is now [0, 1, 2, 1, 2, 1]

And then check that the first element (where the entire string treated as a function) returns 0, and that no elements are below 0 (recall that the empty array [] is falsey in GolfScript):
 (!\{0<},!&

Remember to add an explanation.

@Quincunx Done!

Common Lisp (???)
The idea here was to highlight the flexibiliity of the Lisp reader and actually allow other characters as list delimiters.  Unfortunately, it seems like too much of the other parts of the language syntax (e.g., using 'foo as an abbreviation for (quote foo) and different comment syntaxes (; rather than // for end-of-line comments, and #| … |# instead of /* … */)) probably disqualify this from being a "working" entry.
(defun check-source (x)
  (labels ((s (x y)
             (set-macro-character x y))
           (r (e)
             (s e (get-macro-character #\) nil))
             (lambda (s c)
               (read-delimited-list e s t)))
           (p (b e)
             (s b (r e))))
    (map 'nil #'p "[{<" "]}>")
    (listp (read-from-string (concatenate 'string "(" x ")")))))

(defun check-source(x)(labels((s(x y)(set-macro-character x y))(r(e)(s e(get-macro-character #)()))(lambda(s c)(read-delimited-list e s t)))(p(b e)(s b(r e))))(map'nil #'p"[{<""]}>")(listp(read-from-string(concatenate'string"("x")")))))

This uses the standard Lisp reader (which already handles ( and ), of course), and defines each new set of a delimiters as another list construction syntax.  These are automatically matched (i.e., mismatches result in an error).  This doesn't handle /* ... */ and // comments, but it handles #| ... |# and // comments.  Double quoted strings are handled, including escapes.

Nice work. While I did add the quotes bonus after posting, I am hesitant to change the rules again. I intentionally made the parse rules for this problem not match any real language so that some contestants would write their own scanner. You get the -20, the -30, and the -50 for // comments, but not the -20 for /**/ comments or the -50 for quotes. The last bonus was intended to add substantially more difficulty.

@acbabis Oh, I misread; it's -50 for // and another -50 for /* */?

No, you were right the first time. Its -70 total for both.

Is there any way you can ignore #| ... |# comments? You need to do that to qualify. Perhaps run the input through a RegEx before parsing?

What do you mean "ignore" #| ... |# comments?  They're already ignored (since they're comments).  If you mean "don't treat them as comments", then I'd rather not do that, since the task is to accept an "arbitrary string resembling source code", and something like #| ok, here's where the magic happens... |# (setf *special-character #\@) does resemble source code.

It wouldn't be too hard to undefine those reader dispatch macros, but now it's getting to the point where I'd start demanding a proper grammar for the language we're supposed to be parsing. :)  (If you provide one, though I'd try to parse it.)  Otherwise there are just too many things to get disqualified for.  E.g., should escaped delimiters not be allowed either, e.g., (defun function-with-\]-in-name …), because right now my code would accept that.

The point of the contest is to treat braces as if they are present unless the rules explicitly state otherwise. I realize allowing // and /**/ but not #||# seems arbitrary, but the comment bonus should be regarded as an afterthought. A basic qualifying submission treats all braces as present. EDIT: Since you asked, a formal grammar is on its way xD

Javascript: 392 383 387 345 characters - 210 bonus = 135 points
function x(a){z=1;k="",a=a.replace(/\/\*.*?\*\/|\/\/.*?\n|".*?"|'.*?'/mg,"").split('');try{for(d in a){eval("c=a[d]//%(')k='(%[')k='[%{')k='{%<')k='<%)_(#%]_[#%}_{#%>_<#".replace(/#/g,"')k=k.substr(1);else z=0//").replace(/%/g,"'+k\nif(c=='").replace(/_/g,"')if(k.charAt(0)=='"))}}catch(e){z=0}return''==k&z==1&a.indexOf("'")<0&a.indexOf('"')<0}

It is a function that returns 0 if the input is not valid and 1 if it is.
First, it uses regular expressions to remove the /* ... */, // ... \n, ' ... ' and " ... " sequences.
Second, it decompresses and run a code that iterates the input string, char-by-char, looking for (, [, { and <, stacking them into a string k. When he founds ), ], } and >, it looks the top of the stack and if they match, he pops the stack, otherwise he sets a variable z to zero. If any exception happens, z is set to zero.
In the end, he checks if the stack is empty and no ' or " are left, returning 1 if this is the case and 0 otherwise.
Thanks to @Charles for pointing out bugs in earlier versions.

looks like your regexes are greedy, so they'll return true for somehting like: (/*abc*/) def*/). Aside from that, that'd pretty much be my algorithm

Also, I think the following would fail: ('a quote " in apostrophes!') "and two quotes out of them"

@Charles Thank you. Fixed and reduced it more 42 characters.

flex, (70+4)-50=24
%{
a;
%}
%%
"(" a++;
")" a?a--:exit(0);
"//".*
.
<<EOF>> exit(!a);
%%

In order for compilation to succeed, you need to use flag -lfl so I added 4 to my character count.
flex flex.l
gcc lex.yy.c -lfl

The code reads character by character, incrementing a counter if a ( is detected and decrementing a counter if a ) is detected.  If the counter is zero when a ) is detected, then we know we don't have a matching ( and can exit.  Simple // comments are matched (and ignored) via a regular expression for the minus fifty bonus.

Bash: 369 bytes - 110 bonus = 259
e=exit;function f(){ s=$1;a=X;until [ "$a" = "" ];do a=${s::1};s=${s:1}
if [ "$a" = \( ];then f "$s" \)||$e 1
elif [ "$a" = [ ];then f "$s" ]||$e 1
elif [ "$a" = \< ];then f "$s" \>||$e 1
elif [ "$a" = { ];then f "$s" }||$e 1
elif [ "$a" = \) ]||[ "$a" = ] ]||[ "$a" = \> ]||[ "$a" = } ]
then [ $a = "$2" ]&&return||$e 1;fi;done;[ "$2" = "" ]||$e 1;};f "$1"&&$e 0||$e 1

Scoring:

Handles all four brace types, 4x -20 = -80
handles mismatched brackets, -30

There's probably room to further golf the chain of elifs into && and ||'s, but some odd behaviour started creeping in when I tried so I gave up :)

Suggested an edit for the part you gave up on (and fixed a bug)

I'm afraid your edit is incorrect - it throws line 1: syntax error near unexpected token `done'

JavaScript (ES6), 92 115 Bytes
Oh look, I beat the other JavaScript answer without any bonuses.
c=s=>{d=0;s=s.split("");for(z=0;z<s.length;z++){if(s[z]=="{")d++;if(s[z]=="}")--d;if(d<0)a="N"}return a||d?"N":"Y"}

Ungolfed, dev-friendly, and ES5-(-friendly) version:
function check(str){
    depth = 0;
    str = str.split("");
    for(var z=0;z<str.length;z++){
        if(str[z]=="{") str[z]+=depth++;
        if(str[z]=="}") str[z]+=--depth;
        if(depth<0) return "unmatched";
    }
    return depth;
}

Returns a version of the string with the "depth" of the bracket afterword. I am using this function for evaluation purposes. I might try for some bonuses later.

All this does is make sure the number of { is equal to the number of }; you need to make sure the running sum never gets below 0 to ensure braces are matched. e.g. {}}{ wouldn't be matched.

@ThomasKwa Oversight on my part. Thanks.

Perl, 106 bytes − (3*20 + 30 + 50 + 0 + 0) bonus = −34 points
$_=join"",<>;$a='[^()<>{}[\]]*';while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}exit!/[()<>{}[\]]/

Input is expected from STDIN (multiple lines) and the return is given as exit code, 1 for successful validation and 0 for unmatched braces.
Example for calling:
perl bracevalidator.pl<inputfile;echo $?

The following is supported/validated:

Balanced braces: (..), <..>, {..}, [..].
No mismatch for different brace types.
C++ style comments //.

The idea is to match the innermost balanced braces first and removes them from the string until all brace pairs are gone. If a brace is left, then the return value is 0, otherwise all braces are properly nested and 1 is returned.
First the whole file is read in variable $_:
$_join'',<>;

Variable $a serves as abbreviation for the brace free stuff between an innermost brace pair:
$a='[^()<>{}[\]]*';

The main loop removes the C++ comments and the brace pairs bottom-up:
while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}

Then the remaining string is checked for any remaining brace:
exit!/[()<>{}[\]]/

EcmaScript 6:
!(_=x[z='replace'](/("|').*?\1|\/\*.*?\*\/|[^({<[\]>})]/g,''),_.length-_[z](/[^({<[]/g,'').length)

Bash - 4 chars
cc f

Assuming f is your c source code file
If you want it to print 'yes' or 'no', 43 chars:
cc f;if $?=0;then echo yes;else echo no;fi

doesn't this check more than just matched braces?

Also, it won't compile (<>), so no dice

All this does is try to compile it as C source code

@TheDoctor ...but it doesn't meet any of the requirements or bonuses :/

cc f;if $?=0;then echo yes;else echo no;fi = cc f && echo yes || echo no, assuming the if had [ in the first place.

Python 2.7: 171 bytes - 60 - 30 = 81 points
import sys
b=[]
for c in sys.stdin.read():
 if c in '([{<':b+=[c]
 if c in ')]}>':
    if b[-1]!='([{<'[list(')]}>').index(c)]:print 0==1;break
    b.pop()
else:print len(b)==0

Handles all bracket types and doesn't allow mismatched brackets.

Good work. The -80 bonus should be -60 because handling 1 brace type is required.

Bah, you're right. I can't math.

VB.net 93c
This check to see if BrainF*ck code has balanced square braces.
Function(c$)c.Aggregate(Of Int32)(0,Function(s,i)If(s<0,s,If(i="["c,s+1,If(i="]"c,s-1,s))))=0

Python, 7 bytes
eval(i)

Where i is the input. It handles {, [ and (, ignores braces in quotes, and, does to allow mismatched braces.
On an error, a Syntax error is generated!
Example:
>> eval('([{"("}])')

>> eval('([{(}])')
            ^
SyntaxError: invalid syntax

Edit: This is just a fun partial solution. It does not handle cases such as [ inside {, and {}[] etc.

C# - 380 characters
Continuously reads the user's input until they quit, each time giving back true or false as to whether their input is valid.
using C = System.Console;

namespace P
{
    class P
    {
        static void Main(string[] a) { while(true) C.WriteLine(F(C.ReadLine())); }
        static bool F(string x)
        {
            int l = 0, r = 0;
            foreach (var c in x) { if (c == '[') l++; if (c == ']') { r++; if ( r > l ) return false; }
            return l == r;
        }
    }
}

Condensed form - 239 characters
using C = System.Console;
namespace P{class P{static void Main(string[] a){while(true)C.WriteLine(F(C.ReadLine()));}static bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}}return l==r;}}}

And lastly
the function itself - 112 characters (condensed form)
bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}return l==r;}

Only realised that the bonuses were a good thing after writing this. Genius :p

All of these programs/functions would be useless for use as part of an actual program reader/parser anyway.

TI-BASIC, 39 bytes
cumSum(iPart(2sin(2seq(inString("()",sub(Ans,X,1)),X,1,length(Ans
not(min(Ans or Ans(dim(Ans

cumSum( keeps a running total of the number of braces, then the second line checks if both the minimum and the last element are zero.
Two tricks used:

iPart(2sin(2* maps {0,1,2} to {0,1,-1} so I don't need to match { and } separately.
I or the last element with the whole list, rather than min(Ans), to save a close-paren.


text:
Array Shuffling
Write a program that takes a sorted integer array, shuffles all the elements in such a way that for every i there must exist a j such that, one of the following is satisfied:
a[i] < a[j] < a[i+1]
a[i] > a[j] > a[i+1]

i and j are within the bounds of array.
If there are not many distinct elements, you must show an error.
For example,
Input: 1, 2
Output: Error

Input: 1, 2, 3, 4, 5, 6, 7
Output: 7, 1, 4, 2, 5, 3, 6

Input: 1, 2, 2, 4, 5, 6, 7
Output: 1, 4, 6, 2, 5, 2, 7

Input: 1, 2, 2, 3
Output: Error

Input: 1, 5, 7, 7, 11
Output: Error

There may be more than one possible correctly shuffled arrays.  You just have to solve for 1 correct solution.
Input array can have repeated elements, this requirement makes the solution tricky, otherwise a sort and skip would have worked.
Being able to have duplicates in input also makes it different from The Strange Unsorting Machine for Nefarious Purposes . And a correct solution is much trickier than the that.
The output must be of same size as input array and all elements from the input array must exist at some position in the output array.
How to take input: The program must take input either through console input or a simple delimited text file.
How to output: The program must output to the console.
What to output: Program must output both the input and the output array in following format
Input: 1, 2, 3, 4, 5, 6, 7
Output: 7, 1, 4, 2, 5, 3, 6

If input cannot be shuffled as required, the output should look like
Input: 1, 2, 3
Output: Error

Shortest code (byte count) wins.
BONUS 1: Deduct 10 points from your count if your solution can work on unsorted inputs.
BONUS 2: Deduct 20 points from your count if your solution can find more than 1 (not all) solutions for the same input.  To qualify for this bonus, your additional solution must not be just a reversed output of the other solution.

This is essentially the same as The Strange Unsorting Machine for Nefarious Purposes

It is different because it allows duplicate items in the input.

I've a solution that works for arrays up to seven elements. Seems up to the specifications so far

I've code that finds all solutions, the brute force way. Haskell: u c=filter(\d->and$map((a,b)->any(\x->(a<x&&x<b)||(a>x&&x>b))d)$zip d (tail d))$permutations c ... just need to do the I/O. Of course being haskell I/O is no fun

This question is very similar also: http://codegolf.stackexchange.com/questions/18306/alternating-sort.

That one is completely different. That allows you to violate a[i] < a[j] < a[i+1]
a[i] > a[j] > a[i+1], which is required of this question.  That one outputs {1, 4, 3, 6, 5, 7, 2, 8} for input {1, 2, 3, 4, 5, 6, 7, 8}, which is invalid in this question (because it contains 6, 5 in output)

working on a java implement atm; abusing a exception :P

I assume the Input:  and Output:  strings are not actually part of the I/O format? What about the commas, may I leave them out? Also, do I have to output Error on errors, or can I just declare that errors are indicated by output that doesn't satisfy the conditions? (I assume I can't, but it's worth asking...)

"Input:" and "Output:" are only required for the output.  I need them because I have a test application.  If you really want to skip them just mention in your solution.

"Deduct 20 points from your count if your solution can find more than 1 (not all) solutions for the same input." -- Does this mean it can't be all or that it doesn't have to be all?

No, you can find as many as you want, but you are not required to find all.

Haskell, 311276 (-30 bonus=246)
import Data.List
m=map
w=putStrLn
b=(intercalate",").(m show)
o="Output: "
z[]=[o++"Error"]
z a=m((o++).b)a
main=do
 r<-getLine
 let q=m read(words r)::[Int]
 w$"Input: "++b q
 mapM_ w$z$filter(\d->and$m(\(a,b)->any(\x->(a<x&&x<b)||(a>x&&x>b))d)$zip d(tail d))$permutations q

Compile with ghc, Run from the command line, input is a single line with space delimited numbers, eg echo 1 2 3 4|shuffle. This is a brute force solution so is quite likely to be slow for large input lists. It prints all the solutions.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Generate an understandable sentence
Problem:
Generate a sentence that can be read and understood. It must contain a subject, verb, and object, and tenses and plurals must match. The program must also be able to generate several different sentences to qualify.
Rules:

Hard-coding the sentences is not permitted, and nor is reading them directly from a file (i'm looking at you, unclemeat)
You can have any number of word lists
Submit an example sentence or 2 that have been generated by your program
Any language is accepted
It's a popularity-contest, so the most upvoted answer wins

I think it's clear from some of the answers (MatLab I'm looking at you) that you should modify the rules such that data-mining is not allowed to pull consecutive words from any source.

While I'm being a smartass: since it's purely a popularity contest, someone should just post a HotModelBikini jpg. That'll get more votes than anything.

And if somebody happens to have a list of phrases on the internet somewhere, can I http for them?

@Cruncher - Yes, but you have do generate several unique sentences to use them.

I'll upvote anyone who uses repetitions of "buffalo" or "fish" as sample sentences!

@YiminRong Don't you mean "correct horse battery stapler" ?

Most answers here either mine valid, full sentences from text sources, or generate output that does not meet the criteria. To me, both approaches seem against the spirit of the question! If someone really wants to impress, might I suggest a program that starts with a set of valid sentence structures like [Adjective] [pl. noun] [verb] [adjective] [pl. noun] and pulls from a real dictionary (maybe using one of the Dictionary APIs available out there) to fill in the blanks? I'd write it myself if I had a few minutes to spare! :( After all... Lazy Developers Write Lousy Programs.

Of all the answers below (including my own) I think the one by squeamish ossifrage is the only one so far that's truly in the spirit of this challenge (@BrianLacy I came up here to post that and saw your comment; there you go!). Well, and Yimin Rong's creative interpretation of it too! :)

@BrianLacy I've made my attempt.

"Understandable" is a bit subjective. Would something like "May Axes Labour Police Beat Pledge" or "Foot heads arms body" count?

@Mechanicalsnail LOL. "Foot heads arms body" is so awesome in context. Definitely added to my list of favorite headlines, right next to basically anything the NY Post prints.

@BrianLacy I think my submission will please you, then :)

@BrianLacy, my lazy program tries to use the form (pronoun | [article] [modifier]* [noun conjunction] noun) [adverb]* verb-ish [article] [modifier] noun [preposition noun].  It is, however, lousy at correctly classifying parts of speech given random wordlists.

What differentiates 'word-lists' from 'hard-coding'?

@Pureferret Word lists would be lists of individual words. Hard coding would be a list of complete sentences. With word lists, you would typically need some logic in the program to piece together a complete sentence. With hard coded sentences, you basically just need a print statement.

I’m voting to close this question because it lacks an "objective validity criterion" as required by the [tag:popularity-contest] tag wiki.

@TheFifthMarshal How does it not? The first two sentences do that precisely.

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

Requirements: linux kernel source installed in /usr/src
This pulls random comments out of the kernel source.  Whether the sentences are actually understandable is open to debate.
Examples of actual output:

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

Good one! You should pull them all and submit it as an official fortune database.

You'd better use /usr/src/linux*, as, for instance, gentoo, names the folder /usr/src/linux-$version

Good suggestion.  Edited

"???" best comment ever

Is not first rule 'nor is reading them directly from a file' is violated ?

I'd say searching through system source code and filtering out the text from comments doesn't really count as "reading directly".

It's slower but fewer characters to use shuf -n 1 instead of head and tail

@Plutor: I considered that, as well as sort -R, but it takes too long to run through the whole lot.  Plus this isn't code golf, so who cares about the length

I got 0 => preemptable <0 => BUG and CRC

and Slave Overflow. nice name for a SE website

Under Arch, my /usr/src/ directory is empty. :(

@undergroundmonorail As the description says, "Requirements: linux kernel source installed in /usr/src".  You can get source on Arch with pacman -S.

Matlab
why

example of outputs:
>> 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.

[This is one of Matlab's easter eggs]
EDIT: you can see the code of this function here: why.m

you can see the code here: http://opg1.ucsd.edu/~sio221/SIO_221A_2009/SIO_221_Data/Matlab5/Toolbox/matlab/elmat/why.m

The second example is not a sentence. It's an infinitive phrase.

Must of the answers here produce not only sentences (look at the other high voted answers for example). The task doesn't say it must create only sentences, it says it must be able to produce sentences.

PHP
Given enough time, this will produce all literature, past, present and future. The rules didn't mention that no other text may be produced.
The string 'TOS...' provides a logarithmic scale frequency of the letters to more closely match English. This is used to generate a larger string with the approximate relative letter frequencies.
$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);

Running it, I have discovered such literary gems as:

GO NOW - You as a subject is implied.
IM AOK - I'm A-OK
IM FDR - I'm F(ranklin) D(eleano) R(oosevelt)

Also, numerous invectives to concisely express displeasure with the current situation. [Some letters redacted.]

F**K
S**T

As well, the following using the fine-tuned scaling:

IS IT ON
I AM STU
I SEE HTML

Why, a bunch of monkeys could do the same!

I likes! Now make a program that processes the letters coming out of that and finds understandable sentences! :)

+1 - any chances to automate the discovering part? The task was seemingly to produce one(?) sentence. BTW: how much time did you spend ;)

How did you get F**K and S**T provided there is no * in 'ABCDEFGHIJKMLNOPQRSTUVWXYZ  '?

@glglgl - letters CHIU redacted.

'TOSRWQPPUALRQTTRGUUUQMMLMFZ' doesn't include an 'E', so how did you manage to produce 'I SEE HTML'?

@Ypnypn - The 'TOS...' string represents the frequency of each letter in a logarithmic scale. So A has frequency T, B has frequency O. J has the lowest frequency A which translates to 0, of which the inverse log is 1. The last character is the space, which has frequency Z, or round(exp(25/3.976)) = 538, so spaces occur 538 times more often than J. Just thought it put a neat twist on the monkey-at-a-typewriter problem.

"Given enough time, this will produce all literature, past, present and future." Um, that would be a recursive loop. You would need time in the future to generate sentences in the future and the sentences generated would need to include the output generated in the future to find them.

+1 for "numerous invectives to concisely express displeasure with the current situation"

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

Example output:

Software caused connection abort
  Interrupted system call should be restarted

There are also plenty of valid sentences output that do not have a subject, verb and object:

Timer expired
  File exists

how and when does this terminate? (it does, but I dont understand why)

@Blauhirn the loop termination condition --i evaluates to false when i (a variable of type char with initial value 0) reaches 0 again. If char is unsigned (e.g. ARM), i will immediately wrap around to its largest value (typically 255) and count down to 0. If char is signed (most Intel systems) the behavior is strictly speaking undefined, but usually once it reaches its minimum value (typically -128) it will wrap around to its maximum (typically 127) and count down to 0. So the program will typically print 256 lines in total.

Java
Pulls the intro sentence from a random Wikipedia article:
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 + ".");
    }
}

Sometimes you get unlucky; I try to minimize this by setting a minimum sentence length and filtering out sentences that end with ":" (all disambiguation pages start that way) or contain a "?" (there seem to be many articles with unresolved unknown info marked by question marks). Sentence boundaries are a period followed by whitespace followed by a number or capital letter.
I also filter out text in parentheses (the result is still a valid sentence) to try and remove some periods that aren't sentence boundaries. I filter out square braces to remove source citation numbers. Examples:

Idle Cure was an arena rock band from Long Beach, California.
Self-focusing is a non-linear optical process induced by the change in refractive index of materials exposed to intense electromagnetic radiation.
TB10Cs4H3 is a member of the H/ACA-like class of non-coding RNA molecule that guide the sites of modification of uridines to pseudouridines of substrate RNAs.
The Six-headed Wild Ram in Sumerian mythology was one of the Heroes slain by Ninurta, patron god of Lagash, in ancient Iraq.
Sugar daddy is a slang term for a man who offers to support a typically younger woman or man after establishing a relationship that is usually sexual.
Old Bethel United Methodist Church is located at 222 Calhoun St., Charleston, South Carolina.
Douglas Geers is an American composer.

If you notice any grammar issues, well, that's your fault for not being a diligent Wikipedia editor! ;-)

I like it! +1 +1 +1 ...

There is definitely a difference between "valid" and "understandable". I've got some substrate RNA pseudouridines for you right here, baby.

Also - mostly - of good quality :)

I got this the first time I ran it: Echinolittorina africana/
Litorina africana Philippi, 1847/
Litorina decollata Philippi, 1847/
Littorina africana /
Littorina perplexa Turton, 1932/
Nodilittorina africana./
It seems there are some Wiki pages you should exclude from your search! ;) Haha!
OMG, the second time I ran it, it returned a line from the Wiki page of Mikhail Gorbachev. Who shares my first name. Quite freaky.

@mikhailcazi Aw man! Bad sentences are pretty rare, I'm totally bummed you got a bad first impression, ha. I've edited the code to reject sentences with a "/" in them (goodbye, awesome biochemistry jargon), but wikipedia has a few weird edge cases that are difficult to avoid without adding a lot of complexity to the program. I couldn't find your sentence in a search; it looks like it's a citations section -- I wonder what article it was. Weird.

The '/' weren't actually there! Haha :P I used it to represent new lines. Maybe I shoulda used \n. It's from here: http://en.wikipedia.org/wiki/Afrolittorina_africana. The table on the right, under synonyms :) Anyway, it wasn't a bad impression so don't worry, because that Mikhail Gorbachev thing was pretty cool. And all the sentences after that were normal.

You may find this Physics answer an interesting, recent co-user of one of those articles.

@EmilioPisanty No way! There are ~750,000 articles on Wikipedia. The fact that I randomly picked the one some other guy used, around the same time he used it and that you happened upon that usage (and read that article) and this answer (then read my list and recognized it) kind of blows my mind.

@mikhailcazi Ha, thanks for the page link. I see what happened; my simple code assumes the first
 on the page is the intro... but those little info boxes also use a
 and appear first. Ah well, I can't avoid it without adding lots of complexity (annoyingly, Document neither automatically parses "id" attributes nor provides a method to search for elements given an attribute).

It may be one common but highly unintuitive aspect of probability: once-in-a-million events can be quite common in a world with billions of people. That said, I'm not sure what a formal analysis would say. I was also quite surprised! You may note too that there is no 'other guy' involved.

Oh! No wonder you recognized it! <something classier than lol but not as overused as the last 4 ha's here/> I also find myself wanting to analyze all the SX data dumps to see how often Wikipedia articles are posted.

Some rough numbers: this page has been seen by about 5k people, most of which will be highly internet-active. If you assume an average viewer quotes Wikipedia online about once a day (an underestimate?), you're polling about 35k citations (the past week or so). These won't be evenly distributed, but if you assume they are, you can estimate your chances of each draw hitting an article a viewer just quoted at about 5%. Run it ten times and you get a 40% chance of this happening. Again, these are rough numbers, but they show it's nowhere near as unreasonable as it seems.

@JasonC I always wonder why people use
 in
 elements! Especially when the content is not a paragraph. For this one at least a
 tag would more than suffice.

@JasonC There. At least now those lines from that page won't pop up when anybody else runs your program (changed
 into
)! Didn't someone once say, "If you don't wanna change your code, change the source code!" :P And -damn- it even looks better! ;D

@mikhailcazi Haha! Oh man. Dayum those are some good lookin' bullet points.

Bahahahahaha xD

Soooo... Since this is popularity-contest, I had some fun with eval and with functions. Basically I generate a random number and then execute a random function based on that number (in your face, switch!) via eval.
PHP, ~9k valid outputs
<?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!
";}
function o2(){ echo "a meatball!
";}
function o3(){ echo "a car!
";}
function o4(){ echo "shoes!
";}
function o5(){ echo "pigs!
";}
function o6(){ echo "a telephone!
";}
function o7(){ echo "some bottles of water!
";}
function o8(){ echo "a laptop!
";}
function o9(){ echo "my shorts!
";} //Quote needed
function o10(){ echo "anchovies!
";}
function o11(){ echo "an alarm clock!
";}
function o12(){ echo "every second!
";}
function o13(){ echo "until the end!
";}
function o14(){ echo "sitting!
";}
function o15(){ echo "a sword!
";}
function o16(){ echo "fire!
";}
function o17(){ echo "the dust!
";}
function o18(){ echo "in the bedroom!
";}
function o19(){ echo "a poor ant!
";}
function o20(){ echo "a pencil!
";}

//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."();");

?>

Some outputs...
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 is only ever equal to \n or \r\n, depending on the operating system, but never
 or similar.

@timmyRS Yes, you're right, this is an old comment, I don't know why I wrote that at the time.

PHP + Project Gutenberg
I wrote a PHP script that turns a plain text document into a set of word bigrams, which it then uses to generate random sentences. Here are some of the better examples it generated from the entire plain text version of Patrick Henry's "Give Me Liberty Or Give Me Death" speech, including the Project Gutenberg small print:

The Project Gutenberg Etext of nations, and slavery!

We apologize for the 200th anniversary of this Small Print!

YOU DON'T HAVE NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR INCIDENTAL DAMAGES, But for me, death!

You can try it out for yourself here. Refresh the page for a new batch of sentences.
If you want to run the source code yourself, don't forget to load $src_text with your chosen plain text.

<title>Give Me Liberty Or Give Me Death</title>

A collection of quotes randomly generated from Patrick Henry's speech
Give Me Liberty Or Give Me Death
(and its accompanying Project Gutenberg blurb).

<?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 "

";

  /* 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 "

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

?>

+10 This one really nails the spirit of the challenge! I can't find it now but there used to be an online Google-based sentence generator that worked in a similar way, but the bigrams (or optionally larger n-grams) were derived from Google search results by searching for a word and observing what followed it in the search result preview snippets. Maybe I will recreate it and post it here.

How about this one!  "Sir, we find which have been pleased to improve the contest."  Or this one!  "They tell us you a refund of awful moment to improve the part of Etext 6 Date last updated: May 5, 2005 Officially released for our battles alone. "

But for me, death! :D I wish all licences/agreements ended as strongly.

Haha, "Officially released for our battles alone."

This is the best. "rivet upon us you a kiss"

I got "Nothing." :(

Python
This entry selects words from whole system dictionary. It takes advantage of the fact that you can make most nouns into verbs and vice-versa. It uses a few heuristics to classify words and avoid obvious impossibilities.
It produces a few nearly sane statements:
The snigger westernizes the bacteriologist.
A drizzle stoked the sentiments.

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

And a lot of stuff that sounds like Monty Python making lewd innuendos:
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.

Version 3 has been modified to take any text file as input:

$ 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.

Code (version 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+'.'

The example sentences are making me laugh so hard, I'm crying! xD

cat FILE | COMMAND? UUOC ;)

Thank you @nyuszika7h, I learned something today.  Breaking a habit that old may be hard though...

This smoke toasted some nonresidents.. WOAH.

Bash
Inspired by the Matlab answer. Assumes you have aptitude installed.
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

Possible outputs (screenshot from  this  wikipedia article)

I don't think .                                /----\                        -------/      \                       /               \                      /                |    -----------------/                  --------\    ---------------------------------------------- is a valid sentence.

@svick you win can be a sentence (the object "the argument" is implied). And even if it isn't, the question does not forbid cases where the output isn't valid.

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

Samples:

Buffalo buffalo buffalo.
Buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo.

Unfortunately, it has somewhat poor handling of punctuation and capitalization, but then again those weren't listed as requirements.
Also, here is a reference.

Don't add spaces to the buffalo literals; instead use ' '.join(l). That'll get rid of the trailing space. You can then just append a period.

@BlacklightShining Updated it. Thanks for the suggestion.

I don't think buffalo is a verb...?

@TheDoctor http://dictionary.reference.com/browse/buffalo

Expressed with itertools, print " ".join(takewhile(lambda _: randint(0, 5), repeat("buffalo"))).capitalize() + "."

Rust + Toki Pona
Any language is accepted, so I wrote a program in Rust that generates some sentences in Toki Pona.
Toki Pona is an attempt to create a minimal natural language, and it has a super simple and regular grammar. That's a very useful property for this contest!
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);
}

I don't speak Toki Pona, but I found the syntax of Toki Pona as a set of BNF rules on Wikipedia. I created one struct or enum for each BNF rule, and I annotated them with deriving(Rand), which gives me a way to generate a random Phrase struct for free! Then, I implemented ToStr for each of these structs to convert them to a string.
I intentionnaly left the struct names in french, because the BNF rules I found are in french, and also because it reinfoces the multilingual nature of my submission!
Sample outputs
Some outputs and their translations, that I did based on the BNF rules and a Toki Pona dictionary. I'm sure these translations are mostly wrong, but Toki Pona actually leaves a lot of room for the interpretation of a sentence.

nasin mi tawa la jan  li jaki

While on my trip, someone polluted

monsi  li jaki   li jan ike musi

The butt is dirty and is a funny bad person

sina  li tawa ale jelo e kili tawa e insa

You moved the fruit and the center to the yellow universe
Issues

I don't check if a verb is transitive or not, thus some sentences are grammatically incorrect.
Some structs are recursive, and when a rule can be repeated I randomly choose to output 0, 1 or 2 elements. This can lead to veeeeeery long generated sentences, containing thousands of words...
I cannot really verify the validity of the output, I rely entirely on the BNF syntax, the dictionary, and my own wild guesses :)

sina li tawa ale jelo e kili tawa e insa == "You moved the fruit and the center to the yellow universe" Pretty good for a machine, usually only advanced tp users can use transformative constructions.

monsi li jaki li jan ike musi == The butt (ass? as in jerk?) is dirty and is a funny bad person.

Hey thanks for your comments, @MatthewMartin ! I certainly didn't expect a Toki Pona speaker to view my submission, but I'm glad to know these senteces are not complete gibberish :)

Hint: It's not a code golf.

@nyuszika7h I'm not sure what the purpose of your comment is. Indeed, it's not a code golf, as it's a popularity contest.

Quoting from your answer: "That's a very useful property for this code golf!"

Ok I see, I changed the wording.

Prolog
Use prolog's backtracking and a generative grammar approximating English grammar to generate all possible sentences.
This version has a fairly limited vocabulary and sentence structure, but it should be pretty easy to extend.
The code:
% 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, []).

Run this query:
sentence(L).

to generate all possible sentences in this language.
Some sample outputs:
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] ;

(EDIT: Allow object subordinate clauses).

Any example sentence outputs?

Yeah I put a few samples in the answer. It generates 2520 outputs in total though so I can't post them all...

Python
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!

Could you argue that import antigravity leads to the output I LEARNED IT LAST NIGHT! EVERYTHING IS SO SIMPLE!? :D

Undoubtedly, yes.

Python
As you know, you can do anything in python with few imports.
This simple task can be accomplished with this 2 lines python script.
import random

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

The number of sentences generated by this script is quate huge: 10^12 different sentences.
If reading a sentece takes you ~0.5 sec, then reading them all will take more than 15000 years!
Some sample sentences:

I like the number 0.444371877853
I like the number 0.358614422548

Yet all the generated sentences contains a subject, a verb and an object.
UPDATE:
I received some critiques about some sophisticated words that this complex tool may produce. Here is a slightly longer version which should be in agreement with most of the wordlists.
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))])+'.')

Here are some sample sentences:

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.

I fail to find some of your words in my dictionary

I adjusted my software to better fit your poor dictionary.

Ok. In 15000 years I'll post to certify I've found them all

Playing with the Mathematica internal dictionary:
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

You get lucky, say, 70% of the time.
It generates things like:

a amygdaloid electric circuit
  yonder Parkia was unrestrictive though ragged
  his longanimous society
  Doctor of Education unintelligible reply to kibbutz
  little musical theater against Julius Caesar
  an Tai nuthatch
  mow down in sportive center contra thy niggardliness
  the required extrinsic detergents
  sans necromantic sorcerer
  these vena pectoralis opposite mine latria trophy wife trend-setting investors brown
  what man-portable field of fire
  umbra charmingly whereunto my answer
  another screw-loose debris storm scentless aslant Aral Sea complex waffle
  for professed delight mongoloid type metal

but sometimes:

mine adoption pro least battle of Lutzen would cash draw in during whiles Hejira of the cleaver
  nine common shiner subduction genus Seiurus heartwarming her audience

Oh well, its use of English is better than mine.

VBA/Excel
[edit 2]
Have taught it how to conjugate verbs, examples below are simple past tense:

The moderate wild cocaine slid abreast of the historic instant decision.
  The regional safe chapter snapped inside of the numerous random entity.
  The yellow right domain removed behind the magnetic fragile gender.
  The physical fatal pollution began past the dead poor sensation.
  The cognitive brave theater went to the front of the fragile aware literature.
  The conventional actual output resisted away from the favorite immune site.
  The fixed economic twin recognized out of the evil human necessity.

The relevant code follows, excluding a bunch of boring ancillary parsing and looping functions.  The main parts that are missing are the various word lists (by parts of speech) which do pluralization, tenses, conjugations, etc.
All of the word roots are picked randomly, but I force them to be arranged in a particular sentence pattern:
Debug.Print getWords("ad adj adj nns vpa1s pl ad adj adj nns")

... which is what I used to generate the output above.  It follows the general form of, "The quick red fox jumped over the lazy brown dog."
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

[begin original post]
Still a work in progress, need to add logic for tenses and noun/verb pluralization, viz.:

Your average travel our supposed dose nor a temperature boost beyond my tomato.

... which is parsable, but doesn't make much sense.

The programming enable their dirty fisherman far our pork cast instead no sentence.

Right.  Not really a sentence, but better than some JavaScript error messages.

His appeal lift every live question that my lady outline top her English.

The innuendo routine is almost top-notch tho' ...
Code to follow anon.  Does this contest have a deadline?
[edit 1]
Code that generated the above.
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

Where is your code?

See my edit for the code.

Perl 5
OK, the guts of the program is just this:
use v5.14;
my %pad = (
    ...
);
sub pad { shift =~ s(\{(.+?)\}){pad($pad{$1}[rand(@{$pad{$1}})])}rogue }
say ucfirst pad '{START}';

It's basically a "madlib" engine. To actually generate interesting sentences, you need to populate %pad with some data. Here's an example %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',
  ],
);

Here's some samples of the wisdom I've discovered from that %pad. These sentences have not been edited for length, punctuation, grammar, etc, though I have culled some uninteresting ones and rearranged the order in which the sentences appear - they are no longer in the order they were generated, but instead I'm trying to use them to tell a story: a story I hope you will find both touching and thought-provoking.

Spider webs are short.
Spider webs fascinate regularly.
Short monkeys are sparkling, but spider webs drink greedily.
Sparkling (yet foul-smelling) monkeys followed the tiny (yet sparkling) gorilla.
The summit of Mt Everest welcomed the highly-decorated stegosaur.
Not only the summit of Mt Everest is expensive, but also the cast of television's "Glee" followed the sparkling gorilla.
The cast of television's "Glee" resembles the lilac mailbox.
The expensive mailbox is tall, and the expensive stegosaur jumps Chuck Norris, yet green shoes jumped the beef salad sandwich.
The beef salad sandwich loved Chuck Norris.
Millions of sparkling eels are green (yet ghostly).

Now if you could populate pad programatically

Populating pad programatically is not much of a challenge. Just scrape wiktionary or something. That wouldn't yield such fun sentences though.

It's not much a a challenge,  but I think it's a fun part of it.

Ms Word
I'm not sure if this is acceptable, but since html is, I think this should be also acceptable.
 =rand(1,1)

Sample sentences:

On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document.
You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks.

you can also specify any number of sentences and paragraphs.

A work in progress using JSoup and 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);
        }
    }

}

Issues:

Sentences are too simple
Occasionally 404s (without good handling!)
Only generates one sentence at a time
Uses a switch case!

Sample outputs:

Popoloca prickethes runner beans.
  Tropic of Capricorn beams up bodles.
  Beijing synonymiseds pillow boxes.
  Chukchis enculturateds influencing.

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])];

This fetches the 30 most trending google searches, performs an "I Feel Lucky" search, and then displays a random sentence from that page with at least 3 words.
Examples:
"She was considered a medal favourite in the event."
"Kate graduated from high school a year early."
"April 15, 2014, to promote compliance with the policy on biographies of living people."
"On behalf of Bryan, we, his family, would like to thank everyone for the  outpouring of love, prayers and support."
"This article is about the American basketball player."
"Sorry, your browser either has JavaScript disabled or does not have any supported player."

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

Running it in the console produces
foo is not defined
null has no properties
radix must be an integer at least 2 and no greater than 36

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

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('
') if x.find('<') >= 1][1].split('.')[0])"

output:

Generate a sentence that can be read and understood

Use Stack Exchange's sharing URIs (e.g. /q/21571 instead of /questions/21571/generate-an-understandable-sentence).

Since this isn't code golf, line breaks for readability would be nice.

Shell Scripting
This script will always display the title of the first question that is currently on top of this site. My assumption is the question title will always be human readable. And it will change dynamically. So whenever a new question comes and when the script is executed, it will give the latest question title.
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

Trial 1 output
Find words containing every vowel

Trial 2 output
Hello World 0.0!

EDIT
Not using any files. Without files, I can use the below script.
value1=$(curl "codegolf.stackexchange.com" -s |  w3m -dump -T text/html)
echo "$value1" | grep -A 8 "more tags" | tail -1

Output
Generate an understandable sentence

nor is reading them directly from a file...

I have made the changes to not use a file. Now, it just used the variables. How about this one?

removed down vote!

Yet another Python script
The answer of user3058846 isn't bad, but it displays every sentences, every time. Here, I propose a script that output a random sentence from the 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))

In one line, for code-golf fans:
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, dirty.)
Examples:
>>> 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.

Another fun way in Python
Thanks to @TheDoctor pour the idea :-) Silent the import output and then play with the pseudo-encrypted dict in the module.
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.'
>>>

It's generally bad practice to use shell=True. Although it's not insecure in this case, as you're not taking user input, I would opt for subprocess.Popen(('python', '-c', 'import this')).

Did you know if you can silence the poem of import this, there is a variable in the module this that contains all the text, but encrypted. There's also a dictionary to decrypt it.

@TheDoctor Look my updated answer :D

Python 3
Guaranteed to generate grammatical output!  (Usually.)
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)

To make it perfectly grammatical, delete the underscore from wordregex. This will disallow multi-word entries that lead to bad sentences such as "We zip up you."
Sample run:
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?

Favorite output so far:
They you her.

Look it up: http://en.wiktionary.org/wiki/you#Verb.

Bash
Trying to run a program that exists but is not installed gives this (in 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'

In different distros, it gives you a different sentence.

That's why I said in LM13

Python
Result:
$ 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)

I used the word list from here Find words containing every vowel
Some more rules can be added. For example, if a word ending with "ness" and the word also exist in set without the suffix, then it's a noun.
Source code:
#!/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

Do I really suck at Python and English, or are you outputting 3 nouns instead of 2 nouns and a verb?

@ace Oops, I decided to fix the code at the last minutes :-(

Python 3
Another take at The Zen of Python, inspired by Maxime's answer.
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))

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/