繁体   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