Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 
This sample code scrambles words in text and you still can read the text. Amazing.
Rules:
1) Don't scramble a word with less than 4 characters
2) Keep the first and last character of the word and scramble the rest   
 
Invoke cgi script => Scramble words (Doesn't work any more because my new provider doesn't offer cgi). As an alternatice you can call the Implementation in Javascript).
Script as pure Python script  => Download
 
The same algorithm I implemented on this page together with the source code in Javascript.
 

 

Source files for download:
 
ATTENTION:
Note the following line in the cgi script is very important:
 
     text = re.sub(u"[^a-zA-Z0-9ÄäÖöÜüß \n]", "", unicode(text,'utf-8'))    # nur Buchstaben und Zahlen erlauben

This line deletes all characteres other than alphabetic characters, numbers and umlauts. This gurantees a reflection of the text entered by a website visitor
doesn't allow any XSS (cross site scripting). This doesn't hurt you but visitors of your website.
 
An alternative to disable XSS is to use either
 
    text = cgi.escape(form[inputkey].value,True)        # guard against XSS attacks just in case
 
or even much better the following code sequence
 
    text = xml.sax.saxutils.escape(form[inputkey].value)        # guard against XSS attacks just in case
    text = xml.sax.saxutils.quoteattr(text)        # guard against XSS attacks just in case
 
 
An easy test whether a webpagerejects XSS requests is to enter following text:
<script type="text/javascript">alert("XSS");</script> 
If a window pops up your code is insecure and should be fixed immediately.
 
HTML
 
Download following code: scramble.html
 
<html><title>Scramble</title>
<body>
 
<h1>Buchstaben aller Worte im Text durchmischen/Scramble text</h1>

<P>Dieses kleine Script durchmischt die Buchstaben eines jeden Wortes eines eingegebenen Textes nach folgenden Regeln:</P>
<OL><LI>Ein Wort mit weniger als 4 Buchstaben wird nicht geändert.</LI>
<LI>Ein Wort behält seinen ersten und letzten Buchstaben und alle anderen Buchstaben werden zufällig vertauscht.</LI></OL>
Bei keiner Eingabe wird ein Beispieltext zum durchmischen benutzt.
<hr/>
<P>This small script scrambles characters of words in a text according following rules:</P>
<OL><LI>A word with less than 4 characters is not modified.</LI>
<LI>A word will keep it's first and last character and all other characters are scrambled.</LI></OL>
If no text is provided a sample text will be scrambled.
<hr/>
<form method=POST action="cgi-bin/scramble.cgi">
    <br/>
    <textarea name=textToScramble cols=120 rows=10></textarea>
    <hr/>
    <P><input type=Submit name="Scramble" value="Mischen/Scramble">
</form>
</body></html>
 
Python CGI
 
Download following code:scramble.cgi
 
 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import cgitb; cgitb.enable()

debugme  = False                                 # True=test from cmd line
inputkey = 'textToScramble'
scramblekey  = 'Scramble'      

class dummy:                                     # mocked-up input obj
    def __init__(self, str): self.value = str

import cgi, sys, re, random, os, array
import xml.sax.saxutils
from datetime import datetime

if debugme:
    form = {inputkey: dummy(sys.argv[1])}       # name on cmd line
else:
    form = cgi.FieldStorage()                    # parse real inputs

print 'Content-type: text/html; charset=utf-8'
print

import os
language=os.environ['HTTP_ACCEPT_LANGUAGE']
german=language.lower().startswith('de')

print '<H1>Buchstaben aller Worte im Text durchmischen/Scramble text</H1><HR>'

def scramble(text):

    result=''

    lines=text.split('\n')
    for line in lines:
  
        words = line.split()                    # Worte splitten und Spaces removen

        for word in words:
            if len(word) > 3:
                l=list(word)    
                first=l.pop(0)  
                last=l.pop()    
                random.shuffle(l)
                result+=''.join([first]+l+[last])+ ' ' # alles wieder zusammenbauen
            else:
                if len(word) > 0:                # skip empty words
                    result+=word+' '

        result+='<br/>'

    return result
   
if not form.has_key(inputkey):

    if german:
        text=u"""Aufgrund einer Studie an einer Englischen Universität ist es egal, in welcher Reihenfolge die Buchstaben in
einem Wort stehen, das einzig wichtige dabei ist, dass der erste und letzte Buchstabe am richtigen Platz sind.
Der Rest kann totaler Blödsinn sein, und du kannst es trotzdem ohne Probleme lesen. Das geht deshalb, weil
wir nicht Buchstabe für Buchstabe einzeln lesen, sondern Wörter als Ganzes. Stimmt's?"""
    else:
        text=u"""According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are,
the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can
still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole."""

else:
     text = form[inputkey].value       
     text = re.sub(u"[^a-zA-Z0-9ÄäÖöÜüß \n]", "", unicode(text,'utf-8'))    # nur Buchstaben und Zahlen erlauben

result=scramble(text)

print '<H3>Original Text</H3><P><PRE>'
print text.encode('utf-8')
print '</PRE></P><HR/>'
print '<H3>Text mit durchwürfelten Worten/Scrambled text</H3><P><PRE>'
print result.encode('utf-8')
print '</PRE></P><HR/>'

print """<form method=GET action="../scramble.html"> <input type=Submit value="Neuen Text eingeben/Enter nexw text" name="Return"> </form>"""
print """<form method=PUT action="scramble.cgi"> <input type=Submit value="Text neu mischen/Scramble new text" name="Scramble">""" + '<input type=hidden value="' + text.encode('utf-8') + '" name="textToScramble"> </form>'
 
References:
 
Add comment

*** Note ***

Comments are welcome. But in order to reject spam posts please consider following rules:
  1. Comments with string http are rejected with message You have no rights to use this tag
  2. All comments are reviewed by hand and thus it usually takes one day until a comment will be published.