首页 > 解决方案 > 我怎样才能让python在excel表上找到这个词?

问题描述

我试图让 python 在 excel 表中找到特定的单词。尽管如此,尽管到处搜索如何做到这一点,我还是找不到答案。

import re

with open('ptry.xlsx') as aa:
    for line in aa:
        match = re.search(r'abc', line)
        if match:
            print("yes")
        else:
            print ("no")

这段代码给了我以下结果:

no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no

重新关闭

尽管如此,我期待一个简单的“是”,因为“abc”这个词在我的 Excel 表上。

标签: pythonexcel

解决方案


如果您使用 Excel,我可以建议使用 Openpyxl 吗?

import os
#Change to the dir of your spreadsheet

from openpyxl import load_workbook

wb = load_workbook(filename='Insert your file here', data_only=True)
#data_only=False by default
#If you want to see data instead of formulas, set data_only=True

ws = wb['Sheet1'] #Or whatever your sheet name is

for num_row in range (1, ws.max_row):
    if ws['A{}'.format(num_row)].value=='abc':
        print ('yes')
    else:
        print ('no')
#You can also use ws.max_column

这应该让您大致了解如何使用 openpyxl。如果您还有其他问题,请告诉我。


推荐阅读