使用Python的Excel的词频计数器

时间:2017-06-29 12:24:18

标签: python

我有以下python代码来计算excel文件中出现的次数。即使单元格包含句子,也可以将其写入。但是,由于某些原因,它不起作用,我得到TypeError:类型'Cell'的参数不可迭代。

有人可以提供帮助。

import xlrd
import os
for filename in os.listdir("D:\MyData\MyPythonCodes\Excel reading\search using xlrd"):
if filename.find('xlsx') != -1:
    print(filename)        
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_name("Sheet1")
    values = []
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            if " " in sheet.cell(row,col):
                values.append(str(sheet.cell(row,col).value.split(" ")))
            else:
                values.append(str(sheet.cell(row,col)))
print(values.count("abcd")) times")

1 个答案:

答案 0 :(得分:1)

您可能需要进行以下更改:

import xlrd
import os

for filename in os.listdir("D:\MyData\MyPythonCodes\Excel reading\search using xlrd"):
    if filename.find('xlsx') != -1:
        print(filename)        
        workbook = xlrd.open_workbook(filename)
        sheet = workbook.sheet_by_name("Sheet1")
        values = []
        for row in range(sheet.nrows):
            for col in range(sheet.ncols):
                value = str(sheet.cell(row,col).value)
                if " " in value:
                    for word in value.split(" "):
                        values.append(word)
                else:
                    values.append(value)

        print("%s times" % values.count("abcd"))