【问题标题】:sort words in text by number of times cited in same line按同一行中引用的次数对文本中的单词进行排序
【发布时间】:2019-04-12 00:37:48
【问题描述】:

查找文本中最常用的单词,按每个数字在同一行中打印的数字排序

    grep -oE '[[:alpha:]]' file.txt | sort | uniq -c | sort -nr

它给了

3 linux
3 fedora
2 ubuntu
2 mandriva

我在寻找

3 linux fedora
2 ubuntu mandriva


    grep -oE '[[:alpha:]]' file.txt | sort | uniq -c | sort -nr

结果

 3 linux
 3 fedora
 2 ubuntu
 2 mandriva

我在寻找

 3 linux fedora
 2 ubuntu mandriva

【问题讨论】:

    标签: linux sorting tr


    【解决方案1】:

    我无法在 bash oneliner 中执行此操作,但如果这对您有用,我会在简短的 python 脚本中使用它。

    import os
    
    preMergedList = os.popen("grep -o -E '\w+' file.txt | sort | uniq -c | sort -nr").readlines()
    
    countDict = {}
    for line in preMergedList:
        count, word = line.split(None)
        count = int( count.strip() )
        word = word.strip()
        if not countDict.has_key( count ):
            countDict[count] = ""
        countDict[count] += word + " "
    
    for count, wordString in sorted( countDict.iteritems(), reverse=True ):
        print count, wordString
    
    

    【讨论】:

    • 它有效,但给出了字符数而不是单词数,我在寻找单词
    • 这只是你正在做的基本 grep,我只是从你那里得到的,如果你用 grep -o -E '\w+' 替换它,它应该像那样工作
    • 你说得对,谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    相关资源
    最近更新 更多