我想编写一个脚本,它可以接受一行文本,并告诉我其中是否有任何单词由相同的字母组成。以下是一个例子:
How can you listen if you are not silent?
这里的“listen”和“silent”由完全相同的字母和相同的频率组成。
有什么帮助吗?
答案1
不带评论地呈现:
ruby -rset -e '
readlines.each {|sentence|
p sentence
data = Hash.new {|h,k| h[k] = Set.new}
sentence.scan(/\w+/).each {|word| data[word.chars.sort] << word }
p data.each_value.select {|set| set.size > 1}.collect(&:to_a)
}
' << END
How can you listen if you are not silent?
I saw a tap; it was apt
END
"How can you listen if you are not silent?\n"
[["listen", "silent"]]
"I saw a tap; it was apt\n"
[["saw", "was"], ["tap", "apt"]]
答案2
这将列出句子中每个空格分隔的字符集的频率:
echo 'How can you listen if you are not silent?' \
| tr -cd '[:alpha:][:space:]' \
| tr '[:upper:][:space:]' '[:lower:]\n' \
| while read a; do grep -o .<<<$a | sort | tr -d '\n'; echo; done \
| sort | uniq -c | sort
输出:
1 acn
1 aer
1 fi
1 how
1 not
2 eilnst
2 ouy
它不是很优雅,也许你应该使用除了 shell 之外的其他东西。