
Es liest Text von der Standardeingabe ein und produziert daraus dann einen neuen "zufälligen" Text. Beispiel für Text, der aus dem Buch `Machine Language for The Commodore 64 and Other Commodore Computers` von Jim Butterfield generiert ist:
Variables are placed in the A register only; you may just retype the numbers as requested. Confirm that they seem to be interpreted in the Pulse waveform on Oscillator 1. The stack is often referred to as long as Y is less than $30, which means that it changes the manner in which the VSYNC pulse is desired to occur simultaneously and be transferred to the program is behaving correctly and whether it has finished the whole value. If the envelope is then written to illustrate the problem: we must write one address into the real fun--the creative programming--is up to the other hand, I suppose that you had incorrectly coded LDA #$E0,X and the fetch of MOV data. Therefore, the processor will add one to the indirect address is picked from the beginning; but memory is being pressed.
Code: Alles auswählen
#!/usr/bin/env python
"""Random text generator.
ToDo
----
* Method to join two `Markov` objects.
* Better internal representation of the state graph without actually repeating
states in the list. Map state to a histogram instead.
"""
import random
import sys
__author__ = "Marc 'BlackJack' Rintsch"
__version__ = '0.1.0'
__date__ = '$Date: 2006-04-17 13:28:05 +0200 (Mon, 17 Apr 2006) $'
__revision__ = '$Rev: 842 $'
class Markov:
"""Markov-Chain."""
def __init__(self):
self.state = (None, None)
self.state_map = dict()
def feed(self, words):
"""Feed words into the state.
words : iterable of `str`
Words that are are added to the state graph of the `Markov` object.
"""
for word in words:
self.state_map.setdefault(self.state, list()).append(word)
self.state = (self.state[1], word)
def feed_lines(self, lines):
"""Feed lines into the state.
This method can be used to read a whole file into the state graph
of the `Markov` object.
"""
for line in lines:
self.feed(line.split())
def generate(self, max_words=None):
"""Generate a sequence of words.
If `max_words` is not given, the sequence is endless.
Raises `ValueError` if there are no words added to the `Markov`
object yet.
"""
if not self.state_map:
raise ValueError('empty graph')
generated_words = 0
while True:
state = (None, None)
while True:
try:
word = random.choice(self.state_map[state])
yield word
generated_words += 1
if max_words == generated_words:
raise StopIteration()
state = (state[1], word)
except KeyError:
break
def main():
"""Main function.
Reads from *stdin* and generates text from the read lines.
"""
markov = Markov()
markov.feed_lines(sys.stdin)
print ' '.join(markov.generate(10000))
if __name__ == '__main__':
main()
