簡體   English   中英

在python中查找文本文件的最頻繁和最不頻繁的行

[英]Finding most and least frequent rows of a text file in python

我有一個文本文件,其中只有一列包含文本內容。 我想找出最頻繁的3個項目和最不頻繁的3個項目。 我已經在其他帖子中嘗試了一些解決方案,但無法獲得想要的東西。 我試圖找到如下所示的模式,但是它只輸出所有行。 我也嘗試使用計數器和最常用的功能,但是它們做同樣的事情,即打印文件中的所有行。 任何幫助表示贊賞。

# My Code

import pandas as pd

df = pd.read_csv('sample.txt')

print(df.mode())

您可以使用Python的內置計數器

from collections import Counter

# Read file directly into a Counter
with open('file') as f:
    cnts = Counter(l.strip() for l in f)

# Display 3 most common lines
cnts.most_common(3)

# Display 3 least common lines
cnts.most_common()[-3:]

暫無
暫無

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

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