Reputation: 11321
I want to randomize all the words in a given text, so that I can input a file with English like
"The quick brown fox jumped over the lazy dogs."
and have it output:
"fox jumped lazy brown The over the dogs. quick"
The easiest way I can think to do it would be to import the text into python, put it into a dictionary with a seqence of numbers as keys, then randomize those numbers and get the output. Is there an easier way to do this, maybe from the command-line, so that I don't have to do too much programming?
Upvotes: 1
Views: 171
Reputation: 52493
Quick Solution:
You can randomize lines with sort -R in bash. tr will do string replacement.
example:
echo ".." | tr -s " " "\n" | sort -R | tr "\n" " "; echo
will randomize a string separated by spaces.
Another variation would be converterting all non alphanumerical characters to newlines
| tr -cs 'a-zA-Z0-9' '\n'
explanation:
# tr -c all NOT matching
# tr -s remove all dublicates )
-> randomimizing the lines
| sort -R
-> replacing all newlines with spaces
| tr "\n" " "
-> removing the last space with sed
| sed "s/ *$//"
and finally adding a dot ( and a newline )
; echo "."
Finally : A function to make a real new sentence from another sentence
Features ignoring dublicate space and removing all non-alphanumeric
reading the output makes you sound like master yoda ...
sentence="This sentence shall be randomized...really!"
echo $sentence | tr -cs 'a-zA-Z0-9' '\n' | sort -R | tr "\n" " " | sed "s/ *$//"; echo "."
Output examples:
randomized This shall be sentence really.
really be shall randomized This sentence.
...
Addition: sed explaination ( i know you want it ... )
sed "s/bla/blub/" # replace bla with blub
sed "s/bla*$/blub/" # replace the last occurence of bla with blub
sed "s/ *$//" # -> delete last space aka replace with nothing
would only shuffle the words.
Upvotes: 4
Reputation: 2438
Using Python, from a bash prompt:
echo "The quick brown fox jumped over the lazy dogs." | \
python -c "import random, sys; x = sys.stdin.read().strip().split(' '); \
random.shuffle(x); sys.stdout.write('\"{}\"\n'.format(' '.join(x)))"
Upvotes: 1
Reputation: 36504
In Python:
>>> import random
>>> s = "I want to randomize all the words in a given text, so that I can input a file with English like "
>>> words = s.split()
>>> random.shuffle(words)
>>> ' '.join(words)
'words I so like a can the text, I want a randomize input given with to in all that English file'
Upvotes: 4
Reputation: 195059
quick and dirty:
echo ".."|xargs -n1 |shuf|paste -d' ' -s
your example:
kent$ echo "The quick brown fox jumped over the lazy dogs."|xargs -n1 |shuf|paste -d' ' -s
the jumped quick dogs. brown over lazy fox The
if you don't have shuf
, sort -R
would work too. same idea.
Upvotes: 11