randtext.html
001| '''Random Text.
001|
001| Classes:
001| RandomText
001| RandomWords
001|
001| Functions:
001| generate_alpha_frequency_table (dname, oname)
001| histogram_file (iname, oname)
001|
001| Lambda Functions:
001| Clip (lo,n,hi)
001| AlphaSub (fx,ff)
001| AlphaSet ()
001|
001| Data:
001| NUL, EOL, TAB, SPC, DOT, UCX, LCX
001| AlphaFreqs
001|
001| '''
002|
003| from os import path, listdir
004| from random import randint, choice, random, triangular, gauss
005| from math import fsum
006| from goodies import typename, KWARG, plural
007| from logger import logger
008|
009| Log = logger('RandText')
010| NUL = ''
011| EOL = '\n'
012| TAB = '\t'
013| SPC = ' '
014| DOT = '.'
015| UCX = ord('A')
016| LCX = ord('a')
017|
018| Clip = lambda lo,n,hi: max(lo,min(hi,n))
019|
020| AlphaFreqs = [
021| 0.07661874,
022| 0.01585059,
023| 0.02317437,
024| 0.03940014,
025| 0.11906581,
026| 0.02122051,
027| 0.01819126,
028| 0.06231438,
029| 0.06748642,
030| 0.00122047,
031| 0.00941861,
032| 0.04463175,
033| 0.02898365,
034| 0.06467902,
035| 0.08197751,
036| 0.01528407,
037| 0.00099255,
038| 0.06224923,
039| 0.06575853,
040| 0.08745569,
041| 0.03398662,
042| 0.01023072,
043| 0.02345121,
044| 0.00145807,
045| 0.02443262,
046| 0.00046745,
047| ]
048| AlphaSub = lambda fx,ff: NUL.join([chr(LCX+fx)]*int(ff*30000))
049| AlphaSet = lambda: NUL.join([AlphaSub(fx,ff) for fx,ff in enumerate(AlphaFreqs)])
050|
051|
052|
053| class RandomText:
054| '''Generate paragraphs of random text.'''
055|
056| Alphas = [chr(LCX+n) for n in range(26)]
057| Numbers = ['0','1','2','3','4','5','6','7','8','9']
058| Singles = ['J', 'v', 'O', 'Y']
059|
060| def __init__ (self, **kwargs):
061| '''New RandomText instance.'''
062| self.size = kwargs['paragraphs'] if 'paragraphs' in kwargs else 5
063| self.para_min = kwargs['para_min'] if 'para_min' in kwargs else 1
064| self.para_max = kwargs['para_max'] if 'para_max' in kwargs else 20
065| self.sent_min = kwargs['sent_min'] if 'sent_min' in kwargs else 2
066| self.sent_max = kwargs['sent_max'] if 'sent_max' in kwargs else 17
067| self.word_min = kwargs['word_min'] if 'word_min' in kwargs else 2
068| self.word_max = kwargs['word_max'] if 'word_max' in kwargs else 9
069| self.nmbr_min = kwargs['nmbr_min'] if 'nmbr_min' in kwargs else 1
070| self.nmbr_max = kwargs['nmbr_max'] if 'nmbr_max' in kwargs else 6
071| self.single_f = kwargs['single_f'] if 'single_f' in kwargs else 0.01
072| self.number_f = kwargs['number_f'] if 'number_f' in kwargs else 0.001
073| self.parens_f = kwargs['parens_f'] if 'parens_f' in kwargs else 0.001
074| self.q_mark_f = kwargs['q_mark_f'] if 'q_mark_f' in kwargs else 0.1
075| self.exclam_f = kwargs['exclam_f'] if 'exclam_f' in kwargs else 0.03
076| self.use_freq = kwargs['use_freq'] if 'use_freq' in kwargs else True
077| self.use_html = kwargs['use_html'] if 'use_html' in kwargs else False
078| self.use_sect = kwargs['use_sect'] if 'use_sect' in kwargs else False
079| self.alphas = AlphaSet() if self.use_freq else RandomText.Alphas
080| Log.info(f'RandomText({list(kwargs.keys())})')
081| Log.debug(f'{self.size=}')
082| Log.debug(f'{self.para_min=}')
083| Log.debug(f'{self.para_max=}')
084| Log.debug(f'{self.sent_min=}')
085| Log.debug(f'{self.sent_max=}')
086| Log.debug(f'{self.word_min=}')
087| Log.debug(f'{self.word_max=}')
088| Log.debug(f'{self.nmbr_min=}')
089| Log.debug(f'{self.nmbr_max=}')
090| Log.debug(f'{self.single_f=}')
091| Log.debug(f'{self.number_f=}')
092| Log.debug(f'{self.parens_f=}')
093| Log.debug(f'{self.q_mark_f=}')
094| Log.debug(f'{self.exclam_f=}')
095| Log.debug(f'{self.use_freq=}')
096| Log.debug(f'{self.use_html=}')
097| Log.debug(f'{self.use_sect=}')
098| Log.info()
099| self.content = ''
100|
101|
102| self()
103|
104| def __call__ (self):
105| ''' Generate and return random text.'''
106| ps = [self.paragraph(ix) for ix in range(self.size)]
107| self.content = EOL.join(ps)
108| return self.content
109|
110| def paragraph (self, seq=0):
111| '''Return a random paragraph.'''
112| df = self.para_max - self.para_min
113| ns = int(triangular(self.para_min, self.para_max, df/3))
114|
115|
116| ss = [self.sentence(ix) for ix in range(ns)]
117| para = SPC.join(ss)
118| if self.use_html:
119|
120| n = Clip(0, int(gauss(5,2)), 8)
121| s = '§\n' if self.use_sect and (n < seq) else ''
122| return f'<p style="color:#000000;">{para}</p>{EOL}{s}'
123| return f'{para}{EOL}'
124|
125| def sentence (self, seq=0):
126| '''Return a random sentence.'''
127| df = self.sent_max - self.sent_min
128| nw = int(triangular(self.sent_min, self.sent_max, df/3))
129|
130|
131| ws = [self.word(ix) for ix in range(nw)]
132|
133| if (4 <= len(ws)) and (random() < 0.2):
134| ix = Clip(0, int(gauss(len(ws), 2)), len(ws)-2)
135| ws[ix] = ws[ix]+','
136|
137| if random() < self.q_mark_f:
138| e = '?'
139| elif random() < self.exclam_f:
140| e = '!'
141| else:
142| e = DOT
143|
144| s = SPC.join(ws)
145| if seq and (random() < self.parens_f):
146| return f'({s}{e})'
147| return f'{s}{e}'
148|
149| def word (self, seq=0):
150| '''Return a random word. (Capitalize if first in sequence.)'''
151|
152| if random() < self.single_f:
153| return choice(RandomText.Singles)
154|
155| if random() < self.number_f:
156| return self.number()
157| df = self.word_max - self.word_min
158| nc = int(triangular(self.word_min, self.word_max, df*0.42))
159|
160|
161| cs = [self.alpha(seq+ix) for ix in range(nc)]
162| return NUL.join(cs)
163|
164| def alpha (self, seq=0):
165| '''Return a random character. (Capitalize if first in sequence.)'''
166| a = choice(self.alphas)
167| return a if seq else a.upper()
168|
169| def number (self, seq=0):
170| '''Return a random number.'''
171| nd = randint(self.nmbr_min, self.nmbr_max)
172|
173| ds = [choice(RandomText.Numbers) for _ in range(nd)]
174| return NUL.join(ds)
175|
176| def __bool__ (self): return 0 < len(self.content)
177| def __len__ (self): return len(self.content)
178| def __iter__ (self): return iter(self.content)
179|
180| def __getitem__ (self, ix): return self.content[ix]
181| def __setitem__ (self, ix, value): self.content[ix] = value
182| def __delitem__ (self, ix): del self.content[ix]
183|
184| def __repr__ (self):
185| return f'<{typename(self)} @{id(self):08x}>'
186|
187| def __str__ (self):
188| return self.content
189|
190|
191|
192| RandCount = lambda a,b: int(a + ((b-a) * random()))
193| RandPunct = lambda: ('.' if 0.05 < random() else ('!' if 0.5 < random() else '?'))
194|
195| class RandomWords:
196| '''Generate paragraphs of random words (from a words file).
196|
196| minsec -minimum paragraphs per section [8]
196| maxsec -maximum paragraphs per section [8]
196| minpar -minimum sentences per paragraph [3]
196| maxpar -maximum sentences per paragraph [12]
196| minlin -minimum words per sentence [2]
196| maxlin -maximum words per sentence [20]
196|
196| '''
197| filename = r'C:\CJS\prj\Python\app\dat\words.list'
198|
199| def __init__ (self, **kwargs):
200| '''New RandomWords instance.'''
201| self.minsec = KWARG('minsec', 8, int, kwargs)
202| self.maxsec = KWARG('maxsec', 8, int, kwargs)
203| self.minpar = KWARG('minpar', 3, int, kwargs)
204| self.maxpar = KWARG('maxpar', 12, int, kwargs)
205| self.minlin = KWARG('minlin', 2, int, kwargs)
206| self.maxlin = KWARG('maxlin', 20, int, kwargs)
207| Log.info(f'RandomWords({list(kwargs.keys())})')
208| Log.debug(f'{self.minsec=}')
209| Log.debug(f'{self.maxsec=}')
210| Log.debug(f'{self.minpar=}')
211| Log.debug(f'{self.maxpar=}')
212| Log.debug(f'{self.minlin=}')
213| Log.debug(f'{self.maxlin=}')
214| Log.info()
215| self.wordlist = []
216| self.content = []
217|
218| fp = open(type(self).filename, mode='r', encoding='utf8')
219| try:
220| self.wordlist = list(fp)
221| Log.info(f'loaded: {len(self.wordlist)} word{plural(len(self))}')
222| except:
223| raise
224| finally:
225| fp.close()
226|
227| def __call__ (self, size=500, title=None, ending=None):
228| '''Get a "story" of random words.'''
229| self.content = []
230|
231|
232| if title is not None:
233| self.content.append(f'{title}{EOL}')
234| self.content.append(EOL)
235|
236| length = 0
237| while length < size:
238| sect = self.section()
239| self.content.append(sect)
240| length += len(sect)
241| Log.debug(f'section: {len(sect):,}, count: {len(self)}, total: {length:,}')
242| Log.debug()
243|
244|
245| if ending is not None:
246| self.content.append(EOL)
247| self.content.append(f'{ending}{EOL}')
248|
249| return str(self)
250|
251| def word (self, word_index=1) -> str:
252| '''Return a random word.'''
253| for _ in range(10):
254| w = choice(self.wordlist)
255| if word_index or not w.isnumeric():
256| break
257| return w
258|
259| def sentence (self) -> str:
260| '''Return a sentence of random words.'''
261| nw = RandCount(self.minlin, self.maxlin)
262| ws = [self.word(ix) for ix in range(nw)]
263| ws[0] = f'{ws[0][0].upper()}{ws[0][1:]}'
264| ws[-1] = f'{ws[-1]}{RandPunct()}'
265| return SPC.join(ws)
266|
267| def paragraph (self) -> str:
268| '''Return a paragraph of random sentences.'''
269| ns = RandCount(self.minpar, self.maxpar)
270| ss = [self.sentence() for ix in range(ns)]
271| ss[-1] = f'{ss[-1]}\n'
272| return SPC.join(ss)
273|
274| def section (self) -> str:
275| '''Return a section of random paragraphs.'''
276| np = RandCount(self.minsec, self.maxsec)
277| ps = [self.paragraph() for ix in range(np)]
278| ps[-1] = f'{ps[-1]}\n\xa7\n\n'
279| return EOL.join(ps)
280|
281| def __bool__ (self): return 0 < len(self.content)
282| def __len__ (self): return len(self.content)
283| def __iter__ (self): return iter(self.content)
284|
285| def __getitem__ (self, ix): return self.content[ix]
286| def __setitem__ (self, ix, value): self.content[ix] = value
287| def __delitem__ (self, ix): del self.content[ix]
288|
289| def __repr__ (self):
290| return f'<{typename(self)} @{id(self):08x}>'
291|
292| def __str__ (self):
293| return ''.join(self.content)
294|
295|
296|
297| def generate_alpha_frequency_table (dname, oname='rand-tfreq.out'):
298| '''Generate a character frequency table from a directory of text files.'''
299| UC0, UC1 = UCX, ord('Z')+1
300| LC0, LC1 = LCX, ord('z')+1
301| NR, NC = 32, 8
302| histo = [0]*256
303| tot_bytes = 0
304| tot_chars = 0
305| ns = listdir(dname)
306|
307| for n in ns:
308|
309| fname = path.join(dname, n)
310| fp = open(fname, mode='rb')
311| try:
312|
313| bs = fp.read()
314| cs = str(bs, encoding='latin_1')
315| tot_bytes += len(bs)
316| tot_chars += len(cs)
317| except:
318| raise
319| finally:
320| fp.close()
321|
322| for c in cs:
323| ix = ord(c)
324| histo[ix] += 1
325|
326|
327| ucs = histo[UC0:UC1]
328| lcs = histo[LC0:LC1]
329| tot_alpha = sum(ucs)+sum(lcs)
330|
331| freqs = [(t[0]+t[1])/tot_alpha for t in zip(ucs,lcs)]
332|
333|
334| fp = open(oname, mode='w', encoding='utf-8')
335| try:
336| fp.write(f'total-bytes: {tot_bytes}{EOL}')
337| fp.write(f'total-chars: {tot_chars}{EOL}')
338| fp.write(f'total-alpha: {tot_alpha}{EOL}')
339| fp.write(EOL)
340|
341| for r in range(NR):
342| fp.write(f'[{r*NC:02x}]')
343| for c in range(NC):
344| fp.write(f' {histo[(r*NC)+c]:06d}')
345| fp.write(EOL)
346| fp.write(EOL)
347|
348| bsize = 0
349| for fx,ff in enumerate(freqs):
350| n = int(ff*1000000)
351| fp.write(f'[{fx+1:02d} ({chr(UCX+fx)})] {ff:.8f} {n:6d}{EOL}')
352| bsize += n
353| fp.write(EOL)
354| fp.write(f'total-freqs: {fsum(freqs)}{EOL}')
355| fp.write(f'total-bsize: {bsize}{EOL}')
356| fp.write(EOL)
357| except:
358| raise
359| finally:
360| fp.close()
361|
362| return freqs
363|
364|
365| def histogram_file (iname, oname='rand-histo.out'):
366| '''Generate a character histogram of an input file.'''
367| NR, NC = 32, 8
368| histo = [0]*256
369|
370|
371| fp = open(iname, mode='rb')
372| try:
373| bs = fp.read()
374| except:
375| raise
376| finally:
377| fp.close()
378|
379|
380| for b in bs:
381| histo[b] += 1
382|
383|
384| fp = open(oname, mode='w', encoding='utf-8')
385| try:
386| for r in range(NR):
387| fp.write(f'[{r*NC:02x}]')
388| for c in range(NC):
389| fp.write(f' {histo[(r*NC)+c]:6d}')
390| fp.write(EOL)
391| fp.write(EOL)
392|
393| fp.write(f'NUL: {histo[0x00]:6d}{EOL}')
394| fp.write(f'CR: {histo[0x0D]:6d}{EOL}')
395| fp.write(f'LF: {histo[0x0A]:6d}{EOL}')
396| fp.write(f'SPC: {histo[0x20]:6d}{EOL}')
397| fp.write(f'".": {histo[ord('.')]:6d}{EOL}')
398| fp.write(f'",": {histo[ord(',')]:6d}{EOL}')
399| fp.write(f'"!": {histo[ord('!')]:6d}{EOL}')
400| fp.write(f'"?": {histo[ord('?')]:6d}{EOL}')
401| fp.write(f'"(": {histo[ord('(')]:6d}{EOL}')
402| fp.write(f'")": {histo[ord(')')]:6d}{EOL}')
403| fp.write(EOL)
404|
405| for ax in range(26):
406| a = histo[UCX+ax]
407| b = histo[LCX+ax]
408| fp.write(f'|{chr(UCX+ax)}: {a:6d}|{chr(LCX+ax)}: {b:6d}|{EOL}')
409| fp.write(EOL)
410| except:
411| raise
412| finally:
413| mode=fp.close()
414|
415|
416|
417|
418| def demo_random_words ():
419| """Generate random words (using a word list). """
420|
421| words = RandomWords()
422| words()
423|
424| print(words)
425| Log.info(words)
426| Log.info()
427|
428| return 'Done'
429|
430|
431| if __name__ == '__main__':
432| demo_random_words()
433|
434| '''eof'''
435|