Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Answer

Commonmark migration
Source Link

#Python 3

Python 3

#Python 3

Python 3

Added instructions for making output perfectly grammatical.
Source Link
DLosc
  • 40.7k
  • 6
  • 87
  • 142

Guaranteed to generate grammatical output! (Usually.)

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

Favorite output so far:

They you her.

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

Guaranteed to generate grammatical output!

Guaranteed to generate grammatical output! (Usually.)

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

Favorite output so far:

They you her.

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

Source Link
DLosc
  • 40.7k
  • 6
  • 87
  • 142

#Python 3

Guaranteed to generate grammatical output!

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)

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?

AltStyle によって変換されたページ (->オリジナル) /