2017-02-18 4 views
0

저는 python 3.x 및 openpyxl을 사용하여 Excel .xlsx 파일을 구문 분석합니다.Openpyxl을 사용하여 키워드를 확인한 다음 해당 키워드를 포함하는 셀 옆에있는 숫자를 수정하여 총계를 찾음

각 행에 대해 해당 키워드가 일치하는지 확인하기 위해 열 (C)을 확인합니다. 그렇다면 별도의 목록 변수에 키워드를 추가하고 일치하는 키워드의 수를 결정합니다.

다음 실제 키워드를 다음 셀에 추가하고 전체 키워드를 셀에 추가하려고합니다. 이것이 내가 실제로 문제를 일으키고 결과를 쓰는 곳입니다. 내가 그 ws.iter_rows에, 잘못된 것 (..) 튜플을 반환하고있어 어디 here

import openpyxl 

# Here I read a keywords.txt file and input them into a keywords variable 
# I throwaway the first line to prevent a mismatch due to the unicode BOM 
with open("keywords.txt") as f: 
    f.readline() 
    keywords = [line.rstrip("\n") for line in f] 

# Load the workbook 
wb = openpyxl.load_workbook("results.xlsx") 
ws = wb.get_sheet_by_name("Sheet") 

# Iterate through every row, only looking in column C for the keyword match. 
for row in ws.iter_rows("C{}:E{}".format(ws.min_row, ws.max_row)): 
    # if there's a match, add to the keywords_found list 
    keywords_found = [key for key in keywords if key in row[0].value] 
    # if any keywords found, enter the keywords in column D 
    # and how many keywords into column E 
    if len(keywords_found): 
     row[1].value = keywords_found 
     row[2].value = len(keywords_found) 

지금, 나는 을 이해 keywords.txt 및 results.xlsx 파일의

내용, 수정할 수 없습니다. 각 행에 대해 하나씩, 두 행에 대해 하나씩, 각 행에 대해 하나씩 열을 계산할 수 있습니다. 그러나이 테스트는 행 수가 수만 개가되는 실제 시나리오의 작은 예입니다.

이 문제를 해결하는 가장 좋은 방법은 무엇인지 잘 모르겠습니다. 귀하가 제공 할 수있는 도움에 대해 미리 감사드립니다.

답변

0

해당 셀의 ws['C'] 다음에 offset() 방법을 사용하십시오.

0

찰리에게 offset() 팁을 보내 주셔서 감사합니다. 코드를 약간 수정했는데 이제는 코드를 수정합니다.

for row in ws.iter_rows("C{}:C{}"...) 
    for cell in row: 
    .... 
    if len(keywords_found): 
     cell.offset(0,1).value = str(keywords_found) 
     cell.offset(0,2).value = str(len(keywords_found)) 
관련 문제