簡體   English   中英

從 python 的 txt 文件中取兩列並進行分桶

[英]take two columns from txt file in python and do bucketing

我有一個文本文件,每列用逗號分隔,我只想取最后一列,並為每個獨特的情況打印兩行,並告訴它在文件中附加了多少次。

例如: txt文件:

蘋果、香蕉、梅隆

蘋果、香蕉、梅隆

獼猴桃、香蕉、梅隆

獼猴桃、芒果、香蕉

蘋果、芒果、香蕉

output 應該是:

香蕉梅隆 3

芒果香蕉 2

謝謝

我嘗試實現一些基本的東西,但我不確定這是否符合您的用例,也不確定它是否是這樣做的最佳方式。

def bucketing(filename = 'input.txt'):
    content = [x.strip().split(',')[1:] for x in open(filename, 'r').readlines() if x.strip() != '']
    unique = {'{0} {1}'.format(x[0], x[1]):0 for x in content}

    for item in content:
        unique['{0} {1}'.format(item[0], item[1])] += 1

    output = ''
    for key in unique:
        output += key + ' ' + str(unique[key]) + '\n\n'
    return output.strip()

暫無
暫無

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

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