【问题标题】:How can I make python find this word on an excel sheet?我怎样才能让python在excel表上找到这个词?
【发布时间】:2020-02-18 01:56:49
【问题描述】:

我正在尝试让 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

Repl 已关闭

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

【问题讨论】:

标签: python excel


【解决方案1】:

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

【讨论】:

  • 谢谢森,这很好用!另外,感谢所有提出一些答案的人,非常感谢他们。
【解决方案2】:

可能有更好的方法,但这个方法可以解决问题。在下面的代码中,以文本格式创建了 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")

【讨论】:

    【解决方案3】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2019-06-13
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多