#!/usr/bin/python
# -*- coding: cp1252 -*-
from random import random

f = open('markov.txt')
TextIn = f.read()
f.close()

TextIn = TextIn.replace('\n', ' ')
TextIn = TextIn.split(' ')
TextIn = [n for n in TextIn if n not in '']

# ExampleDict = {
# 'er':  { 'geht'  : 0.5,
#          'steht' : 0.5 },
# 'sie': { 'geht'  : 0.3,
#          'laeuft': 0.7 }
# }

WortDict = {}

# WortDict mit Anzahl des Vorkommens von Wortfolgen füllen

for w in range(len(TextIn)-1):
    if (TextIn[w] != ''):
        if not WortDict.has_key(TextIn[w]):
            WortDict[TextIn[w]] = {}
        if not WortDict[TextIn[w]].has_key(TextIn[w+1]):
            WortDict[TextIn[w]][TextIn[w+1]] = 1.0
        else:
            WortDict[TextIn[w]][TextIn[w+1]] += 1.0

# Anzahl in Wahrscheinlichkeit umrechnen

for (Wort, NextDict) in WortDict.items():
    # print "---", Wort
    # Gesamtzahl nächster Wörter berechnen
    TotalCount = 0
    for (NextWort, Count) in NextDict.items():
        TotalCount += Count
    # Zahl für jedes nächste Wort durch Gesamtzahl teilen
    for (NextWort, Count) in NextDict.items():
        WortDict[Wort][NextWort] = WortDict[Wort][NextWort]/TotalCount
        # print NextWort, WortDict[Wort][NextWort]

# Neuen Text erstellen

CurWort = 'Der'
LenText = 200
Text = CurWort

for n in range(LenText):
    x = random()
    ProbSum = 0
    for (NextWort, Prob) in WortDict[CurWort].items():
        if (x>=ProbSum) and (x < ProbSum+Prob):
            Text += " " + NextWort
            CurWort = NextWort
        ProbSum += Prob

print Text[:Text.rfind('.')+1]
z = raw_input('Enter beendet das Programm. ')
