我有如下数据集:
"485","AlterNet","Statistics","Estimation","Narnia","Two and half men"
"717","I like Sheen", "Narnia", "Statistics", "Estimation"
"633","MachineLearning","AI","I like Cars, but I also like bikes"
"717","I like Sheen","MachineLearning", "regression", "AI"
"136","MachineLearning","AI","TopGear"
诸若此类
我想找出最常见的词对。
(Statistics,Estimation:2)
(Statistics,Narnia:2)
(Narnia,Statistics)
(MachineLearning,AI:3)
这两个词可以是任意顺序的,也可以是彼此之间的任何距离。
有人能在python中提出一个可能的解决方案吗?这是一个非常大的数据集。
任何建议都会受到高度赞赏。
这就是我在275365年度的建议之后所尝试的
@275365我尝试使用从文件中读取的输入进行以下操作
def collect_pairs(file):
pair_counter = Counter()
for line in open(file):
unique_tokens = sorted(set(line))
combos = combinations(unique_tokens, 2)
pair_counter += Counter(combos)
print pair_counter
file = ('myfileComb.txt')
p=collect_pairs(file)
文本文件的行数与原始文件相同,但在特定行中只有唯一的标记。我不知道我做错了什么,因为当我运行这个程序时,它会将单词拆分成字母,而不是将输出作为单词的组合。当我运行这个文件时,它输出拆分字母,而不是预期的单词组合。我不知道我在哪里犯了错误。
发布于 2014-01-23 02:49:09
你可以从这样的事情开始,取决于你的语料库有多大:
>>> from itertools import combinations
>>> from collections import Counter
>>> def collect_pairs(lines):
pair_counter = Counter()
for line in lines:
unique_tokens = sorted(set(line)) # exclude duplicates in same line and sort to ensure one word is always before other
combos = combinations(unique_tokens, 2)
pair_counter += Counter(combos)
return pair_counter
结果:
>>> t2 = [['485', 'AlterNet', 'Statistics', 'Estimation', 'Narnia', 'Two and half men'], ['717', 'I like Sheen', 'Narnia', 'Statistics', 'Estimation'], ['633', 'MachineLearning', 'AI', 'I like Cars, but I also like bikes'], ['717', 'I like Sheen', 'MachineLearning', 'regression', 'AI'], ['136', 'MachineLearning', 'AI', 'TopGear']]
>>> pairs = collect_pairs(t2)
>>> pairs.most_common(3)
[(('MachineLearning', 'AI'), 3), (('717', 'I like Sheen'), 2), (('Statistics', 'Estimation'), 2)]
您是否希望将数字包含在这些组合中?既然你没有特别提到排除他们,我就把他们包括在这里。
编辑:使用文件对象
你上面发布的第一次尝试的功能非常接近于工作。您唯一需要做的就是将每一行(即字符串)更改为元组或列表。假设您的数据与上面发布的数据完全相同(每个术语周围都有引号,各术语之间有逗号),我建议使用一个简单的修复方法:您可以使用ast.literal_eval
。(否则,您可能需要使用某种正则表达式。)有关ast.literal_eval
的修改版本,请参阅下面的内容
from itertools import combinations
from collections import Counter
import ast
def collect_pairs(file_name):
pair_counter = Counter()
for line in open(file_name): # these lines are each simply one long string; you need a list or tuple
unique_tokens = sorted(set(ast.literal_eval(line))) # eval will convert each line into a tuple before converting the tuple to a set
combos = combinations(unique_tokens, 2)
pair_counter += Counter(combos)
return pair_counter # return the actual Counter object
现在您可以这样测试它:
file_name = 'myfileComb.txt'
p = collect_pairs(file_name)
print p.most_common(10) # for example
发布于 2014-01-23 22:59:22
除了数数所有的配对之外,你没什么可以做的。
显而易见的优化是提前删除重复的单词和同义词,执行词干(任何减少不同标记数量的操作都是好的!),并且只在(a,b)
中计数a<b
(在您的示例中,只计算statistics,narnia
或narnia,statistics
,而不是同时计算!)。
如果内存不足,请执行两次传递。在第一次传递中,使用一个或多个散列函数来获得候选筛选器。在第二次传递中,只计算通过此筛选器的单词(MinHash / LSH样式筛选)。
这是一个简单的并行问题,因此也很容易分发到多个线程或计算机。
https://stackoverflow.com/questions/21297740
复制相似问题