我必须在多个文件中存储每个单词的字数。在Perl中,我使用了散列的散列,比如$wcCount{$file}{$word}
。我不知道如何在python中做类似的事情。我试过用这种效果的东西,但显然没用
for line in fh:
arr = line.split()
for word in arr:
key = filename + word #creates a unique identifier for each word count
freqdict[key] += 1
我读了另一个stackoverflow的类似问题,但是它不允许在单词再次计数时更新值。在
输入是多个充满单词的文件。输出应该只是一个单词(作为命令行参数)的频率列表。在
假设您有Hamlet,并且您想要计算唯一的单词。在
您可以:
如果要打印从最常见到最少的单词:
^{pr2}$印刷品:
如果需要Dict的嵌套Dict(如Perl示例所示),可以执行以下操作:
我建议集合。计数器,如果您使用的是Python 2.7或更高版本:
您可以这样查看计数:
^{pr2}$使用
Counter
并使用元组(文件名、单词)作为键值,您可能可以不受影响,例如:但是,您还可以根据文件名创建一个初始字典,其中有一个
^{pr2}$Counter
,然后进行更新,以便您可以访问一个“散列”,就像文件名作为键一样,然后是单词计数,例如:相关问题 更多 >
编程相关推荐