我刚刚开始使用Python,我遇到了以下问题:
想象一下,我有以下列表清单:
list = [["Word1","Word2","Word2","Word4566"],["Word2", "Word3", "Word4"], ...]
显示的列和行都是出现的单词(无论哪个列表)。
我想要的是一个程序,它计算每个列表中单词的外观(按列表)。
图片是第一个列表之后的结果。
有没有一种简单的方法来实现类似的东西或类似的东西?
编辑:
基本上我想要一个List / Matrix,告诉我当单词1也在列表中时,出现了多少次2-4566字,依此类推。
所以我会得到每个单词的列表,显示与该单词有关的所有其他4555个单词的绝对频率。
所以我需要一种迭代所有这些单词列表并构建结果列表的算法
答案 0 :(得分:2)
据我所知,你想创建一个矩阵,显示每对单词中两个单词所在的列表数。
首先,我们应该修复一组独特的单词:
lst = [["Word1","Word2","Word2","Word4566"],["Word2", "Word3", "Word4"], ...] # list is a reserved word in python, don't use it as a name of variables
words = set()
for sublst in lst:
words |= set(sublst)
words = list(words)
第二,我们应该用零定义一个矩阵:
result = [[0] * len(words)] * len(words) # zeros matrix N x N
最后我们填写给定列表中的矩阵:
for sublst in lst:
sublst = list(set(sublst)) # selecting unique words only
for i in xrange(len(sublst)):
for j in xrange(i + 1, len(sublst)):
index1 = words.index(sublst[i])
index2 = words.index(sublst[j])
result[index1][index2] += 1
result[index2][index1] += 1
print result
答案 1 :(得分:1)
我发现很难理解你真正要求的是什么,但我会尝试做一些假设:
如果这些假设是正确的,那么该表格与您提供的列表无法正确对应。如果我的假设是错误的,那么我仍然相信我的解决方案可能会给你灵感或一些关于如何正确解决它的想法。最后,我并不认为我的解决方案在速度或类似方面是最佳的。
OBS !!我使用python的内置词典,如果你打算用数千个单词填充它们,这可能会变得非常慢!看看:https://docs.python.org/2/tutorial/datastructures.html#dictionaries
frq_dict = {} # num of appearances / frequency
uqe_dict = {} # unique
for list_b in list_A:
temp_dict = {}
for word in list_b:
if( word in temp_dict ):
temp_dict[word]+=1
else:
temp_dict[word]=1
# frq is the number of appearances
for word, frq in temp_dict.iteritems():
if( frq > 1 ):
if( word in frq_dict )
frq_dict[word] += frq
else
frq_dict[word] = frq
else:
if( word in uqe_dict )
uqe_dict[word] += 1
else
uqe_dict[word] = 1
答案 2 :(得分:0)
我设法找到了自己问题的正确答案:
list = [["Word1","Word2","Word2"],["Word2", "Word3", "Word4"],["Word2","Word3"]]
#Names of all dicts
all_words = sorted(set([w for sublist in list for w in sublist]))
#Creating the dicts
dicts = []
for i in all_words:
dicts.append([i, dict.fromkeys([w for w in all_words if w != i],0)])
#Updating the dicts
for l in list:
for word in sorted(set(l)):
tmpL = [w for w in l if w != word]
ind = ([w[0] for w in dicts].index(word))
for w in dicts[ind][1]:
dicts[ind][1][w] += l.count(w)
print dicts
获取结果:
[' Word1',{' Word4':0,' Word3':0,' Word2':2}],[ ' Word2',{' Word4':1,' Word1':1,' Word3':2}],[' Word3',{' Word4':1,' Word1':0,' Word2':2}],[' Word4' ,{' Word1':0,' Word3':1,' Word2':1}]]