gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:11 24 4
gpt4 key购买 nike

我正在尝试编写一个 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' — 我可以使用什么方法/模块/循环结构来查明是否不止一次出现列表中的两个项目在列表中彼此相邻?

最佳答案

您要查找的内容称为双字母组(两个单词的对)。您通常会在文本挖掘/NLP 类型的问题中看到这些问题。试试这个:

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

返回:

Counter({('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, ('purple', 'red'): 1, ('blue', 'yellow'): 1, ('blue', 'green'): 1, ('yellow', 'green'): 1, ('green', 'yellow'): 1})

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

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

关于python - 在 CSV 文件中查找多次出现的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com