This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Replace random words in a string of text with asterisks

Help for those learning Tcl or writing their own scripts.
Post Reply
l
leprechau
Voice
Posts: 2
Joined: Fri Oct 03, 2008 9:56 pm
Contact:

Replace random words in a string of text with asterisks

Post by leprechau »

I'm not sure exactly who it was, and I can't find the exact post now, but hopefully whoever needed it will find it here. This was a topic I read awhile ago and just thought I would post something I threw together in TCLSH this evening. Hope it helps someone.

Code: Select all

proc wordMask {text {num {1}}} {
	set txtl [expr {[llength $text] -1}]; set rlist [list]
	if {$num > [llength $text]} {set num [llength $text]}
	while {[llength $rlist] < $num} {
		set x [expr {round(rand()*$txtl)}]
		lappend rlist $x; set rlist [lsort -unique $rlist]
	}
	set outs [split $text]; foreach idx $rlist {
		set outs [lreplace $outs $idx $idx [regsub -all -- {[[:alnum:]]} [set rep [lindex $outs $idx]] {*}]]
		lappend reps [regsub -all -- {[\!\.\?\;\:\"]} $rep {}]
	}; return [list [join $outs] [join $reps]]
}
Usage example:

Code: Select all

foreach {mask reps} [wordMask $text 5] {}
This gives you two variables you can use later on as follows....

Code: Select all

puts "Masked Text -> $mask"
Will give you: Masked Text -> Hello **** *'** ** **** ****!

Code: Select all

puts "Replaced Words -> $reps"
Will give you: Replaced Words -> dear I'll be home soon

That's it...pretty simple and if you read the code in the proc declaration you can see the script will default to replacing 1 word in the passed text, but any other number can be specified if desired.
leprechau@EFnet
User avatar
TCL_no_TK
Owner
Posts: 509
Joined: Fri Aug 25, 2006 7:05 pm
Location: England, Yorkshire

Post by TCL_no_TK »

MC_8's More Tools dose this, read the script for more information on the syntax. :D
Post Reply