【问题标题】:how to generate list of (unique) words from text file in ubuntu?如何从 ubuntu 中的文本文件生成(唯一)单词列表?
【发布时间】:2013-05-05 13:18:45
【问题描述】:

我有一个 ASCII 文本文件。我想使用一个或多个 Ubuntu 命令从该文件中生成所有“单词”的列表。单词被定义为分隔符之间的字母数字序列。分隔符默认为空格,但我也想尝试使用其他字符,如标点符号等。换句话说,我希望能够指定分隔符字符集。我如何只产生一组独特的单词?如果我还想只列出至少 N 个字符长的单词怎么办?

【问题讨论】:

  • 基本上你需要一个 bash 或更一般的 shell 脚本。

标签: ubuntu unique words


【解决方案1】:

你可以使用 grep:

-E '\w+' 搜索字词

-o 仅打印与% cat temp 匹配的行部分

一些例子使用“快速棕色狐狸跳过懒狗” 而不是“Lorem ipsum dolor sit amet,consectetur adipiscing elit” 例如文本。

如果你不在乎单词是否重复

% grep -o -E '\w+' temp
Some
examples
use
The
quick
brown
fox
jumped
over
the
lazy
dog
rather
than
Lorem
ipsum
dolor
sit
amet
consectetur
adipiscing
elit
for
example
text

如果您只想打印每个单词一次,不考虑大小写,您可以使用排序

-u 每个单词只打印一次

-f 告诉 sort 在比较单词时忽略大小写

如果你只想要每个单词一次

% grep -o -E '\w+' temp | sort -u -f
adipiscing
amet
brown
consectetur
dog
dolor
elit
example
examples
for
fox
ipsum
jumped
lazy
Lorem
over
quick
rather
sit
Some
text
than
The
use

您也可以使用tr 命令

echo the quick brown fox jumped over the lazydog | tr -cs 'a-zA-Z0-9' '\n'
the
quick
brown
fox
jumped
over
the
lazydog

-c 用于指定字符的补码; -s 挤出重复的替换; 'a-zA-Z0-9' 是一组字母数字,如果您在此处添加一个字符,则输入不会在该字符上分隔(参见下面的另一个示例); '\n' 是替换字符(换行符)。

echo the quick brown fox jumped over the lazy-dog | tr -cs 'a-zA-Z0-9-' '\n'
the
quick
brown
fox
jumped
over
the
lazy-dog

当我们在非分隔符列表中添加“-”时,会打印惰性狗。其他的输出是

echo the quick brown fox jumped over the lazy-dog | tr -cs 'a-zA-Z0-9' '\n'
the
quick
brown
fox
jumped
over
the
lazy
dog

tr 总结:任何不在-c 参数中的字符都将充当分隔符。我希望这也能解决您的分隔符问题。

【讨论】:

  • 如果您希望它对目录(及其子目录)起作用,那么只需执行grep -o -E -r '\w+' . | sort -u -f -r 就可以递归搜索子目录。 . 目录 替换了temp 文件
【解决方案2】:

这是我的词云状链

cat myfile | grep -o -E '\w+' | tr '[A-Z]' '[a-z]' | sort | uniq -c | sort -nr

如果您有 tex 文件,请将 cat 替换为 detex

detex myfile | grep -o -E '\w+' | tr '[A-Z]' '[a-z]' | sort | uniq -c | sort -nr

【讨论】:

    【解决方案3】:

    这应该对你有用:

    tr \ \\t\\v\\f\\r \\n | | tr -s \\n | tr -dc a-zA-Z0-9\\n | LC_ALL=C sort | uniq
    

    如果您想要至少五个字符长的字符,请将tr 的输出通过grep ..... 传输。如果您想要不区分大小写,请将tr A-Z a-z 粘贴在sort 之前的某个位置。

    请注意,LC_ALL=Csort 正常工作所必需的。

    我建议您阅读 man 页面,了解您在此处不理解的 ant 命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多