计算频率

时间:2014-11-27 14:11:29

标签: python-3.x

我试图弄清楚如何计算单词标签I-GENE和O出现在文件中的频率数。

我正在尝试计算的文件示例如下:

45 WORDTAG O cortex 
2 WORDTAG I-GENE cdc33 
4 WORDTAG O PPRE 
4 WORDTAG O How
44 WORDTAG O if

我正在尝试计算与类别(例如O)相同的同一类别(例如I-GENE)中的单词[0](第1列)的总和

在这个例子中:

I-GENE类别的单词总和为2
并且O类别的单词总和是97

我的代码:

import os

def reading_files (path):

    counter = 0

    for root, dirs, files in os.walk(path):

        for file in files:
            if file != ".DS_Store":
                if file == "gene.counts":
                    open_file = open(root+file, 'r', encoding = "ISO-8859-1")
                    for line in open_file:
                        tmp = line.split(' ')

                        for words in tmp:

                            for word in words:
                                if (words[2]=='I-GENE'):
                                   sum = sum + int(words[0]
                                if (words[2] == 'O'):
                                   sum = sum + int(words[0])

                            else:
                                print('Nothing')

                        print(sum)

1 个答案:

答案 0 :(得分:0)

我认为你应该删除单词循环 - 你不使用它

for word in words:

我会使用字典 - 如果你想解决这个问题。 在阅读文件时,请填写以下字典:   - 如果你已经拥有dict中的密钥 - >增加它的价值   - 如果是新密钥,则添加到dict,并将值设置为它的值。

def reading_files (path):
freqDict = dict()
...
for words in tmp:
    if words[2] not in freqDict():
        freqDict[words[2]] = 0
    freqDict[words[2]] += int(words[0])

创建字典后,您可以将其返回并与关键字一起使用,或者您可以为该函数传递关键字,并返回该值或只打印它。 我更喜欢第一个 - 使用尽可能少的文件IO操作。您可以使用从内存中收集的数据。

对于这个解决方案,我写了一个包装器:

def getValue(fDict, key):
if key not in fDict:
    return "Nothing"
return str(fDict[key])

所以它会像你的榜样一样。

这不是必要的,但是一个好的做法:当你不再使用它时关闭文件。

相关问题