gpt4 book ai didi

bash - 使用awk对ngram单词进行排序

转载 作者:行者123 更新时间:2023-12-05 09:23:36 37 4
gpt4 key购买 nike

我有以下内容,想使用 awk 命令进行排序

 capital of the country
capital of
capital
capital of the
capital is
capital is the
capital is the like

我希望这些像这样排序

 capital
capital is
capital of
capital is the
capital is the like
capital of the
capital of the country

是否可以使用 awk 命令进行完全相同的排序,还是需要通过编程来处理?

最佳答案

这在 Python 中非常简单:

import sys

# get input filename from command line
_, infile = sys.argv

# read the data in to a list
with open(infile, "rt") as f:
lines = f.readlines()

# define a function to use for sorting
def ngram_key(line):
words = line.split()
# We want to sort by, first, number of words; second, the text.
# Return a tuple with two values, number of words and the text.
return (len(words), line) # same number of words should sort together

# sort the lines using the desired rule
lines.sort(key=ngram_key)

# print the lines to standard output
print(''.join(lines))

但是 AWK 没有 Python 类型的 key= 特性。如果 Python 适合您,那么此答案将有效。如果你真的需要 AWK,那么我推荐使用 DSU(Decorate,Sort,Undecorate)。将行存储在数组中,但在每行前面加上单词数(作为固定长度的字符串)。然后将所有具有相同单词数的行一起排序,就像在 Python 程序中一样。排序完成后,去掉固定长度的数字,你就得到了排序列表。 DSU 也称为“Schwartzian 变换”。

http://en.wikipedia.org/wiki/Schwartzian_transform

所以这是使用上述技术在 AWK 中的一个可行解决方案:

{
# Store lines prefixed by number of words in line.
# As numbers are fixed-length and zero-prefixed, an ASCII
# sort will also be a numeric sort.
a[NR] = sprintf("%04d%s", NF, $0)
}

END {
# sort the stored lines
asort(a)
# strip off the prefix and print each line
for (i = 1; i <= NR; ++i) {
line = substr(a[i], 5)
print(line)
}
}

恕我直言,Python 更简洁、更容易理解。在 Python 中,您必须明确地从命令行读取参数,而在 AWK 中则不需要;但在其他方面,我认为 Python 更容易理解。

编辑:所以,这是输出。这是你想要的吗?我以为是,但我只是再次查看了您的示例输出,结果并不完全相同。如果您的示例完全正确,那么我实际上不明白您要做什么。

这是首先按字数排序然后按字数排序时得到的结果:

capital
capital is
capital of
capital is the
capital of the
capital is the like
capital of the country

另外,AWK 版本中有一个错误,它没有打印最后一行。固定。

关于bash - 使用awk对ngram单词进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20417898/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com