我有一个文本文件test.in
如下:
english<tab>walawala
foo bar<tab>laa war
foo bar<tab>laa war
hello world<tab>walo lorl
hello world<tab>walo lorl
foo bar<tab>laa war
所需输出应为:
^{pr2}$新列是行数除以总行数。在
目前我正在做这个:
cat test.in | uniq -c | awk '{print $2"\t"$3"\t"$1}' > test.out
但这只给了我行数,而不是概率。而且,我的文件非常大,比如1000000000行,每列至少有20个字符。在
如何正确快速地获得所需的输出?
有没有一种Python的解决方案同样快?
下面是一个纯AWK解决方案:
它使用AWK的数组和特殊变量
NR
,它跟踪行数。在让我们仔细分析一下代码。第一个街区
^{pr2}$对输入中的每一行执行一次。这里
$0
表示每一行,它被用作数组a
上的索引,因此,只计算每行的出现次数。在第二个街区
在输入的末尾执行。此时,
a
包含输入中每一行的出现次数,并按行本身进行索引:因此,通过循环它,我们可以打印一个行和相关出现的表(我们除以行的总数,NR
)。在这有几个优点。它迭代文件中的行而不是加载整个文件,它利用现有的
Counter
功能,它可以排序,并且清楚地知道发生了什么。在注意uniq只计算重复的行数,并且必须在其前面加上sort,以便考虑文件中的所有行。对于
sort | uniq -c
,以下使用collections.Counter的代码更有效,因为它根本不需要对任何内容进行排序:此脚本输出
^{pr2}$对于你描述中给出的输入。在
但是,如果您只需要合并连续的行,比如
uniq -c
,请注意使用Counter
的任何解决方案都会给出问题中给出的输出,但是您的uniq -c
方法将而不是。uniq -c will be
的输出:不
如果这是您想要的行为,您可以使用^{} :
不同之处在于,给定一个
test.in
包含您指定的内容,uniq管道将而不是生成您在示例中给出的输出,而您将得到:由于这不是您的输入示例所说的,可能是没有
sort
就不能使用uniq
来解决问题,那么您需要求助于我的第一个示例,Python肯定会比Unix命令行更快。在顺便说一句,这些功能在所有python>;2.6中都是一样的。在
相关问题 更多 >
编程相关推荐