使用 python & xlrd 计算 Excel sheet 中特定单词的出现次数

Count number of occurences of specific words in Excel sheet using python & xlrd

我正在编写一个 python 脚本,用于查找与脚本位于同一目录中的 excel sheets(我有大约 10 个)并计算出现的次数这些文件中的特定单词(如 cloud、vmware、python 等)然后将每个单词的总数写入文本文件。我正在使用 python 和 xlrd 来执行此操作。每个 excel 文件都有一个名为 details 的 sheet,这是信息所在的位置。每个文件有 2 列和大约 26 行。

for filename in os.listdir(path):


if filename.find('xls') != -1:
    print filename        
    workbook=xlrd.open_workbook(filename)
    sheet=workbook.sheet_by_name("Details")
    values = []
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            values.append(unicode(sheet.cell(row,col).value))

            print values.count("cloud")

我正在使用 for 循环遍历每个文件的列和所有行,然后将所有值添加到列表中。然后我使用名为值的列表进行计数。我需要某种计数来计算每个单词的总数,因为一切都发生在 for 循环中,否则会显示每个文件的计数。但不幸的是,由于某种原因它不起作用。我还需要设置一个像字典之类的东西,里面有我想要计算的所有单词,但我不知道该怎么做。任何帮助将不胜感激。

对于您提出的新问题,如果您提供输入数据的示例可能会有所帮助。和预期的输出

我认为你应该改变

values.append(unicode(sheet.cell(row,col).value))

if " " in sheet.cell(row,col):
    values.append(str(sheet.cell(row,col).value.split(" ")))
else:
    values.append(str(sheet.cell(row,col)))

在这种情况下,您的 values 包含所有单词(包括标点符号)。您可以删除标点符号并分别使用 String and Collections 个模块计算单词数。

from collections import Counter
import string
words = Counter(word.lower().strip(string.punctuation) for word in values)

print words 应该打印出 excel 文件中的所有单词,并在它们前面显示一个计数器。

单元格可能包含也可能不包含多个单词,因此您必须在替换标点符号后 split。到这里,用翻译图搞定了:

import xlrd
import os
from string import punctuation, translate
from collections import Counter

def count_words_trans():
    filename = u'test.xls'
    sheet_no = 1  # sheet is selected by index here
    path = '.'
    punctuation_map = dict((ord(c), u' ') for c in punctuation)

    for filename in os.listdir(path):
       if filename.endswith('.xls'):
          print filename
          workbook = xlrd.open_workbook(filename)
          sheet = workbook.sheet_by_index(sheet_no)
          values = []
          for row in range(sheet.nrows):
              for col in range(sheet.ncols):
                  c = sheet.cell(row, col)
                  if c.ctype == xlrd.XL_CELL_TEXT:
                     cv = unicode(c.value)
                     wordlist = cv.translate(punctuation_map).split()
                     values.extend(wordlist)

          cnt = Counter(values)
          print sum(cnt.values()),' words counted,',len(cnt),' unique'

'action:run' 之类的文本已正确拆分为 2 个单词(与仅删除标点符号不同)。翻译方法是 unicode 安全的。为了提高效率,只读取包含文本的单元格(没有空格、没有日期、没有数字)。
您将获得词频列表:

for w in cnt.most_common():
    print '%s %s' % w