231ab5c96fc99ee0efce88878566125947132640
[wolnelektury.git] / apps / lesmianator / views.py
1 # Create your views here.
2
3 import pickle
4 from django.shortcuts import render_to_response
5 from django.template import RequestContext
6 from random import randint
7
8 import os.path
9
10
11 def _choose_word(word):
12     try:
13         choices = sum((_dictionary[word][post] for post in _dictionary[word]))
14         r = randint(0, choices - 1)
15
16         for post in _dictionary[word]:
17             r -= _dictionary[word][post]
18             if r < 0:
19                 return post
20     except KeyError:
21         return ''
22
23 # load dictionary on start, it won't change
24 try:
25     f = open(os.path.join(os.path.dirname(__file__), 'dictionary.p'))
26     _dictionary = pickle.load(f)
27 except:
28     _dictionary = {}
29
30
31 def poem(request):
32     letters = []
33     word = u''
34     empty = -10
35     left = 1000
36     if not _dictionary:
37         left = 0
38     while empty != 3 and left:
39         letter = _choose_word(word)
40         letters.append(letter)
41         word = word[-2:] + letter
42         if letter == u'\n':
43             empty += 1
44         else:
45             empty = 0
46         left -= 1
47
48     poem = ''.join(letters).strip()
49
50     return render_to_response('lesmianator/poem.html', 
51                 {"object": poem},
52                 context_instance=RequestContext(request))