繁体   English   中英

如何让 python 在 excel 表上找到这个词?

[英]How can I make python find this word on an excel sheet?

我试图让 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 表上。

如果您使用的是 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。 如果您还有其他问题,请告诉我。

可能有更好的方法,但这可以解决问题。 在下面的代码中,以文本格式创建 excel 文件的副本,然后创建一个列表并检查文件中的“单词”。

import pandas as pd

df = pd.read_excel("ptry.xlsx")
df.to_csv("ptry.txt")

filex = open("ptry.txt", "r")
filex_string = filex.read()
filex_list = filex_string.split(",")

if "word" in filex_list:
    print("True")
else:
    print("false")
import openpyxl

excel_var = openpyxl.load_workbook('excelname.xlsx')

sheet = excel_name.get_sheet_by_name('sheetname')

for row in sheet.iter_rows(min_row=minr, min_col=5, max_col=11, max_row=maxr):
    match = re.search(r'abc', line)
    if match:
        print("yes")
    else:
        print("no")

请注意,您应该限制 for 循环中的行和列有一个 vars minr 和 maxr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM