有没有一种简单的方法来随机化给定文本中的所有单词?也许在BASH?

时间:2013-05-22 16:13:23

标签: python bash

我想随机化给定文本中的所有单词,以便我可以输入一个英文文件,如

"The quick brown fox jumped over the lazy dogs." 

并输出:

"fox jumped lazy brown The over the dogs. quick"    

我能想到的最简单的方法是将文本导入到python中,将其放入一个数字序列作为键的字典中,然后将这些数字随机化并获得输出。是否有一种更简单的方法可以从命令行执行此操作,这样我就不必进行太多编程了?

4 个答案:

答案 0 :(得分:11)

快速而肮脏:

echo ".."|xargs -n1 |shuf|paste -d' ' -s

你的例子:

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

如果您没有shufsort -R也可以。同样的想法。

答案 1 :(得分:4)

快速解决方案:

您可以在bash中使用 sort -R 随机化行。 tr 将进行字符串替换。

示例:

echo ".." | tr -s " " "\n" | sort -R | tr "\n" " "; echo

将随机化由空格分隔的字符串。

另一种变体是将所有非字母数字字符转换为换行符

| tr -cs 'a-zA-Z0-9' '\n'

说明:

# tr -c       all NOT matching 
# tr -s       remove all dublicates )

- >随机化线条

| sort -R  

- >用空格替换所有换行符

| tr "\n" " "

- >用sed删除最后一个空格

| sed "s/ *$//"
  

最后添加一个点(和一个换行符)

; echo "." 

最后:从另一个句子中创建一个真正新句子的功能

功能忽略dublicate space并删除所有非字母数字

阅读输出让你听起来像大师尤达......

sentence="This sentence shall be randomized...really!"

echo $sentence | tr -cs 'a-zA-Z0-9' '\n' | sort -R | tr "\n" " " | sed "s/ *$//"; echo "."

输出示例:

randomized This shall be sentence really.
really be shall randomized This sentence.

...

添加:sed explainlated (我知道你想要它......)

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

只会改变话语。

答案 2 :(得分:4)

在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'

答案 3 :(得分:1)

使用Python,从bash提示符开始:

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)))"