bugfix for book infobox
[wolnelektury.git] / apps / lesmianator / views.py
1 # Create your views here.
2
3 import cPickle
4 from django.shortcuts import render_to_response
5 from django.template import RequestContext
6 from random import randint
7
8
9 def _choose_word(word):
10     try:
11         choices = sum((_dictionary[word][post] for post in _dictionary[word]))
12         r = randint(0, choices - 1)
13
14         for post in _dictionary[word]:
15             r -= _dictionary[word][post]
16             if r < 0:
17                 return post
18     except KeyError:
19         return ''
20
21 # load dictionary on start, it won't change
22 from django.conf import settings
23
24 try:
25     f = open(settings.LESMIANATOR_PICKLE)
26     _dictionary = cPickle.load(f)
27 except:
28     _dictionary = {}
29
30
31 def poem(request):
32     letters = []
33     word = u''
34     empty = -10
35     left = 1000
36     lines = 0
37     if not _dictionary:
38         left = 0
39     # want at least two lines, but let Lesmianator end his stanzas
40     while (empty < 2 or lines < 2) and left:
41         letter = _choose_word(word)
42         letters.append(letter)
43         word = word[-2:] + letter
44         if letter == u'\n':
45             # count non-empty lines
46             if empty == 0:
47                 lines += 1
48             # 
49             if lines >= 2:
50                 empty += 1
51             lines += 1
52         else:
53             empty = 0
54         left -= 1
55
56     poem = ''.join(letters).strip()
57
58     return render_to_response('lesmianator/poem.html', 
59                 {"object": poem},
60                 context_instance=RequestContext(request))