簡體   English   中英

按同一行中引用的次數對文本中的單詞進行排序

[英]sort words in text by number of times cited in same line

查找文本中最常用的單詞,並按每個數字在同一行中打印的數字排序

    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

我無法在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM