【问题标题】:Python: How do I search a string from one XLSX to be in another XLSX file?Python:如何从一个 XLSX 中搜索一个字符串以在另一个 XLSX 文件中?
【发布时间】:2015-07-15 16:26:44
【问题描述】:

我有两个 XLSX 文件(Cookies 和 Cream),我想知道 A 列(Cookie 中)每一行中的值是否存在于 D 列(Cream 中)的某些行中。

使用openpyxl,我导出了以下代码:

for mrow in range(1, Cookies.get_highest_row() +1):
    for arow in range(1, Cream.get_highest_row() +1):
        if cookies['A' + str(mrow)].value == cream['D' + str(arow)].value:
               print(cookies['A' + str(mrow)].value)
               break

尽管这确实按预期工作,但这需要很长时间才能执行,因为 cookie 包含大约 7000 行,而 cream 有超过 24,000 行。

感谢您的帮助

【问题讨论】:

  • 我对任何 XLSX API 都不是很熟悉,cookiescream 是什么类型的对象?将所需的列(即 A 和 D)转换为常规 python 列表并使用它们会更便宜吗?
  • @user3267581 这听起来是个好主意。 Cookies 和 Cream 的对象是可以访问和篡改每一列的电子表格。如何轻松地将 7000 和 24,000 项从 Excel 表加载到列表中?我将如何比较这两个列表?理想情况下,我希望它告诉我以下信息(可能是文本文件中的列表?):“这些是以下‘字符串’,其中包含在 Cookies 中但不在 Cream 中”
  • 正如我所说,我不知道您使用的是什么库。你能提供任何信息吗?也许考虑将列实际转换为 python sets,这样您就可以轻松地轻松执行差和交运算。列表似乎足够小。

标签: python excel search find openpyxl


【解决方案1】:

这是我的工作,但请注意,这不使用 openpyxl 包的任何特殊方法(正在处理)。但是,它应该足以加快您的工作速度。该算法总体上更快,并且避免了 openpyxl 中的一些陷阱(所有单元的内存分配,请参阅中途警告:http://openpyxl.readthedocs.org/en/latest/tutorial.html

def findAinD(cookies, cream):  # assumes that cookies and cream can be treated as such in the for loop will fail otherwise
    A1 = []
    D1 = []

    for mrow in range(1, Cookies.get_highest_row() + 1):
        A1 += cookies['A' + str(mrow)]
        D1 += cream['D' + str(mrow)]

    A1.sort()  # Alphabetical
    D1.sort()  # ^


    for i, cookie in enumerate(A1): # Enumerate returns the index and the object for each iteration
        A1[i] = D1.index(cookie)    # If cookie IS in D, then A1[i] now contains the index of the first occurence of A[i] in D
                                    # If cookie is not, then the result is -1, which is never an index,
                                    #  and we filter those out before round 2 (not shown)

    return A1

使用此方法,并通过检查否定、过滤等方式分析返回的对象。

【讨论】:

  • 使用ws.iter_rows() 循环工作表,无需担心max_row。同样,使用ws.cel(row=1, column=4) 进行编程访问。为了手动方便,添加了索引。如果您想检查成员资格,请使用字典而不是列表,因为 index() 取决于列表的大小。
【解决方案2】:

openpyxl 确实允许您直接访问列,但您仍然需要自己检查单元格。您的代码将是这样的:

cookies = load_workbook("cookies.xlsx")
cream = load_workbook("cream.xlsx")
ws1 = cookies['sheetname']
ws2 = cream['sheetname2']

cookies_a = ws1.columns[0]
cream_d = ws1.columns[4]

for c1, c2 in zip(cookies_a, cream_d):
    if c1.value == c2.value:
         break

如果您有非常大的文件,这会很慢。可以使用解析代码在字符串和使用它们的单元格之间创建参考图,但最好使用 xlwings 之类的东西来自动化 Excel 并使其完成工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2014-02-13
    • 2013-08-08
    相关资源
    最近更新 更多