【问题标题】:Filter rows in Excel file by specific words按特定单词过滤 Excel 文件中的行
【发布时间】:2017-10-10 16:20:14
【问题描述】:

我一直在努力设计一个在 excel 文件中搜索“N”个单词的 Python 代码。在存在任何“N”个单词的地方,python 代码应该输出这些单词所在的整行。我正在搜索一个 Excel 文件中出现的多个单词。

假设有一个这种类型的 excel 文件(比如说它叫做File.xlsx):

ID    Date        Time      Comment
123   12/23/2017  11:10:02 Trouble with pin
98y   01/17/2016  12:45:01 Great web experience. But I had some issues.
76H   05/39/2017  09:55:59 Could not log into the portal.

根据以上数据,问题是:
如果我要搜索单词“pin”和“log”并在上面的 excel 文件中找到它,我希望我的 python 代码输出 line1 并在它下面输出 line3。

从概念上讲,我可以想办法解决这个问题,但是 Python 的实现让我很困惑。此外,我在 Stack Overflow 中进行了广泛搜索,但找不到解决此问题的帖子。

非常感谢任何和所有帮助。

【问题讨论】:

  • 从这里的 python 包之一开始:python-excel.org。由于您只想读取 excel 文件(不写入excel 文件),您可以使用xlrd
  • 您是否要更新File.xlsx 的内容,创建一个过滤文件,例如filtered.xlsx 还是只显示所需的行?

标签: python excel search


【解决方案1】:

有很多方法可以做到这一点,因为有很多 python 包可以读取 Excel 文件 (http://www.python-excel.org/),但 xlrd 可能是最直接的方法:

import xlrd                             # package to read Excel file

book = xlrd.open_workbook("File.xls")   # open the file
sh = book.sheet_by_index(0)             # get first Excel sheet

words = ['pin', 'log']                  # list of words to search

for rx in xrange(sh.nrows):             # for each row in file
    for word in words:                  # for each word in list
        if word in str(sh.row(rx)):     # check of word in row
            print 'line',rx             # if so, print row number

输出:

line 1
line 3

【讨论】:

    【解决方案2】:

    这是一个使用openpyxl 模块的解决方案,我已经成功地用于许多项目。

    行索引从一个开始,包括标题,因此如果您不想计算标题,我们需要将索引计数减少 1 row - 1

    from openpyxl import load_workbook
    
    wb = load_workbook(filename = 'afile.xlsx')
    ws = wb.active
    search_words = ['pin' , 'log']
    
    for row in xrange(1,ws.max_row + 1):
        for col in xrange(1,ws.max_column + 1):
            _cell = ws.cell(row=row, column=col)
            if any(word in str(_cell.value) for word in search_words):
                print "line {}".format(row - 1)
                break
    >>> 
    line 1
    line 3
    

    如果你想输出实际的行,那么 只需添加以下print_row 函数

    def print_row(row):
        line = ''
        for col in xrange(1,ws.max_column + 1):
            _cell = ws.cell(row=row, column=col).value
            if _cell:
                line += ' ' + str(_cell)
        return line
    

    并将print "line {}".format(row - 1) 替换为print print_row(row)

    >>> 
     123 2017-12-23 00:00:00 11:10:02 Trouble with pin
     76H 05/39/2017 09:55:59 Could not log into the portal.
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多