Python - 在 csv 文件中显示具有重复值的行

Inf*_*ano 5 python csv dictionary

我有一个包含多列的 .csv 文件,其中一列填充了随机数,我想在那里找到重复的值。如果有 - 奇怪的情况,但毕竟这是我想要检查的 - 我想显示/存储存储这些值的完整行。

为了说清楚,我有这样的东西:

第一,随便,230,随便,等等
第二,随便,11,随便,等等
第三,随便,46,随便,等等
第四,随便,18,随便,等等
第五,随便,14,随便,等等
第六,随便,48 ,无论哪个,等等
第七,随便,91,随便,等等
第八,随便,18,随便,等等
第九,随便,67,随便,等等

我想要:

第四,随便,18,随便,等等
第八,随便,18,随便,等等

为了找到重复的值,我将该列存储到字典中,并计算每个键以发现它们出现的次数。

import csv
from collections import Counter, defaultdict, OrderedDict

with open(file, 'rt') as inputfile:
        data = csv.reader(inputfile)

        seen = defaultdict(set)
        counts = Counter(row[col_2] for row in data)

print "Numbers and times they appear: %s" % counts
Run Code Online (Sandbox Code Playgroud)

我看到

Counter({' 18 ': 2, ' 46 ': 1, ' 67 ': 1, ' 48 ': 1,...})

现在问题来了,因为我没有设法将密钥与重复链接起来并在以后计算它。如果我做

for value in counts:
        if counts > 1:
            print counts
Run Code Online (Sandbox Code Playgroud)

我只会拿钥匙,这不是我想要的和每一个值(更不用说我不仅要打印,还要打印整行......)

基本上我正在寻找一种方法

If there's a repeated number:
        print rows containing those number
else
        print "No repetitions"
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Sar*_*009 7

试试这可能对你有用。

entries = []
duplicate_entries = []
with open('in.txt', 'r') as my_file:
    for line in my_file:
        columns = line.strip().split(',')
        if columns[2] not in entries:
            entries.append(columns[2])
        else:
            duplicate_entries.append(columns[2]) 

if len(duplicate_entries) > 0:
    with open('out.txt', 'w') as out_file:
        with open('in.txt', 'r') as my_file:
            for line in my_file:
                columns = line.strip().split(',')
                if columns[2] in duplicate_entries:
                    print line.strip()
                    out_file.write(line)
else:
    print "No repetitions"
Run Code Online (Sandbox Code Playgroud)