在CSV文件中查找多次出现的对

时间:2015-06-05 02:17:20

标签: python list python-2.7 csv find-occurrences

我正在尝试编写一个Python脚本,该脚本将搜索CSV文件并确定两个项目彼此相邻时出现的次数。

例如,假设CSV如下所示:

red,green,blue,red,yellow,green,yellow,red,green,purple,blue,yellow,red,blue,blue,green,purple,red,blue,blue,red,green 

我想找到“红色,绿色”彼此相邻的次数(但我想要的解决方案不仅仅是针对此CSV中的单词)。

到目前为止,我认为可能将CSV转换为列表可能是一个好的开始:

import csv
with open('examplefile.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print your_list

返回:

[['red', 'green', 'blue', 'red', 'yellow', 'green', 'yellow', 'red', 'green', 'purple', 'blue', 'yellow', 'red', 'blue', 'blue', 'green', 'purple', 'red', 'blue', 'blue', 'red', 'green ']]

在此列表中,有三次出现'red', 'green' - 我可以使用什么方法/模块/循环结构来确定列表中是否存在多个出现的两个项目列表中的对方?

2 个答案:

答案 0 :(得分:4)

你要找的是bigrams(两个单词对)。您通常会在文本挖掘/ NLP类型问题中看到这些问题。试试这个:

from itertools import islice, izip
from collections import Counter
print Counter(izip(your_list, islice(your_list, 1, None)))

返回:

  

计数器({('red','green'):3,('red','blue'):2,('yellow','red'):   2,('green','purple'):2,('blue','blue'):2,('blue','red'):2,   ('purple','blue'):1,('red','yellow'):1,('green','blue'):1,   ('紫色','红色'):1,('蓝色','黄色'):1,('蓝色','绿色'):1,   ('黄色','绿色'):1,('绿色','黄色'):1})

如果您只需要获取超过1次的项目,请将Counter对象视为python dict。

counts = Counter(izip(your_list, islice(your_list, 1, None)))
print [k for k,v in counts.iteritems() if v  > 1]

所以你只有相关的对:

  

[('red','blue'),('red','green'),('yellow','red'),('green',   'purple'),('blue','blue'),('blue','red')]

请参阅我借用了一些代码的帖子:Counting bigrams (pair of two words) in a file using python

答案 1 :(得分:1)

这将同时检查'red','green''green','red'组合:

pair = ('red', 'green')
positions = [i for i in xrange(len(l)-1) if ((l[i],l[i+1]) == pair or (l[i+1],l[i]) == pair)]
print positions
>>> [0, 7] # notice that your last entry was 'green ' not 'green'

输出打印模式开始的第i个索引。

使用您的示例进行测试(最后更正为 'green '

l = [['red', 'green', 'blue', 'red', 'yellow', 'green', 'yellow', 'red', 'green', 'purple', 'blue', 'yellow', 'red', 'blue', 'blue', 'green', 'purple', 'red', 'blue', 'blue', 'red', 'green ']]
l = l[0]

# add another entry to test reversed matching
l.append('red')

pair = ('red', 'green')
positions = [i for i in xrange(len(l)-1) if ((l[i],l[i+1]) == pair or (l[i+1],l[i]) == pair)]

print positions
>>> [0, 7, 20, 21]

if positions > 1:
    print 'do stuff'
相关问题