【问题标题】:For loop counter is resetting in an internal while loop. Showing a fixed value in while loop and not a changing oneFor 循环计数器正在内部 while 循环中重置。在 while 循环中显示固定值而不是变化的值
【发布时间】:2021-07-16 10:20:03
【问题描述】:

代码的想法是首先从 Excel 表中获取一些数据并对其进行修改,然后将其与文本文档进行交叉比较。下面的代码与它下面的代码一起继续。

import xlsxwriter

workbook1 = xlsxwriter.Workbook('Imports.xlsx')
worksheet1 = workbook1.add_worksheet()
workbook2 = xlsxwriter.Workbook('Modified.xlsx')
worksheet2 = workbook2.add_worksheet()

workbook1.close()
workbook2.close()

import pandas as pd
import openpyxl
from openpyxl.styles import Font
import re
    
df1 = pd.read_excel('Employees.xlsx', sheet_name='Sheet1', usecols="B",)

writer=pd.ExcelWriter('Imports.xlsx')

# Writing dataframes into columns
df1.to_excel(writer,index=False,startcol=0)
writer.save()

wb = openpyxl.load_workbook("Imports.xlsx")
ws = wb["Sheet1"]

i = 0
print("Text replacement part 1 of 4")
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value 
        if s != None and re.search('^Mr ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^Mr ','',s,flags=re.I)
                
        if s != None and re.search('^Ms ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^Ms ','',s,flags=re.I)
                
        if s != None and re.search('^Mrs ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^Mrs ','',s,flags=re.I)
                
        if s != None and re.search('^Miss ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^Miss ','',s,flags=re.I)
                
        if s != None and re.search('^s ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^s ','',s,flags=re.I)                

# Text replacement for list so names in are same format
print("Text replacement part 2 of 4")
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value                
        if s != None and re.search(' \(S\)$',s,flags=re.I): 
                ws.cell(r,c).value = re.sub(' \(S\)','',s,flags=re.I)
                
        if s != None and re.search(' \(F\)$',s,flags=re.I): 
                ws.cell(r,c).value = re.sub(' \(F\)','',s,flags=re.I)
                
          
# Text replacement for list so names in are same format
print("Text replacement part 3 of 4") 
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value                      
        if s != None and re.search('  ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('  ',' ',s,flags=re.I)  
                
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value
        if s != None and re.search(' $',s,flags=re.I): 
                ws.cell(r,c).value = re.sub(' $','',s,flags=re.I)
                
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value
        if s != None and re.search('^ ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^ ','',s,flags=re.I)

print("Text replacement part 4 of 4")
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value
        if s != None and re.search('^D ',s,flags=re.I): 
                ws.cell(r,c).value = re.sub('^D ','',s,flags=re.I)
                
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = ws.cell(r,c).value
        if s != None and re.search(' \(L\)$',s,flags=re.I): 
                ws.cell(r,c).value = re.sub(' \(L\)$','',s,flags=re.I)
                ws.cell(r,3).value = ws.cell(r,c).value
                ws.cell(r,c).value = ''
                
ws['C1'].value = 'Not Employed'                
ws['C1'].font = Font(bold=True)   
                
# Saving another file      
wb.save('Imports.xlsx')

writer2=pd.ExcelWriter('Modified.xlsx')

fs1 = pd.read_excel('Imports.xlsx', sheet_name='Sheet1', usecols="A")
fs1 = fs1.sort_values(['ALL_NAME'],ascending=[True])

fs1.to_excel(writer2,index=False,startcol=0)

writer2.save()
count = 0
count2 = 0




#read input file
fin = open("users.txt", "rt")
#read file contents to string
data = fin.read()
#replace all occurrences of the required string
data = data.replace('  Full name: ', '')
data = data.replace('  Account disabled: ', '')
data = data.replace('  User login: ','')
#close the input file
fin.close()
#open the input file in write mode
fin = open("users.txt", "wt")
#overrite the input file with the resulting data
fin.write(data)
#close the file
fin.close()


wb1 = openpyxl.load_workbook("Modified.xlsx")
ws1 = wb1["Sheet1"]

test = 0




searchfile = open("users.txt", "r") 
    #print(ws1.cell(r,1).value)
   

for i, line in enumerate(searchfile):
    global match
    match = 0
    global a 
    a = i
    l = searchfile.readline(i)
    # finding first search boundary 
    if re.search('^  dn: ',l,flags=re.I):
        if match == 0:
            boole = True
            while boole == True:
                l3 = searchfile.readline(a)
                # finding end boundary in the file for data
                if re.search('  objectclass: ',l3,flags=re.I):
                    boole = False
                else:
                    a+=1
    

基本上下面的代码就是问题出现的地方。我希望代码迭代整个 excel 文件并将每个单元格与文本文件中定义的边界内的每一行进行比较。然而,while 循环中的值 r 被重置为 2,而在它进入 while 循环之前,它似乎工作得很好。

        for r in range(2,ws1.max_row+1):
            #print(r)
            while i < a:
                #print(r)
                l2 = searchfile.readline(i)
            
                if re.search("soa$",l2,flags=re.I) and match == 0: 
                    match = 1
                elif re.search('TC$',l2,flags=re.I) and match == 0:
                    match = 1
                elif re.search(l2,ws1.cell(r,1).value,flags=re.I) and match == 0:
                    ws1.cell(r,2).value = "MATCH"
                    match = 1
                
                i+=1
                
            if match == 0:
                ws1.cell(r,4).value = "NO MATCH"

                    
searchfile.close()
wb1.save("Modified.xlsx")

当在 while 循环中打印 r 时,它包含一个值 2 并且在 while 循环之外,但仍在 for 循环中它按预期工作。我不知道为什么这个值没有在 while 循环中被翻译。有什么想法吗?

【问题讨论】:

    标签: python excel regex for-loop while-loop


    【解决方案1】:

    我认为无论你得到多少 2 都是你的 while 循环经历的循环数。我看不到“a”被初始化为什么,但我确实看到您从未在 for 循环中重置“i”。它进入for循环,r = 2一次,它进入while循环r = 2,但是它循环了很多次,然后回到r现在=3的for循环,再也不会进入while循环,因为我现在是永远大于 a。

    【讨论】:

    • 这个想法是,在第一个 for 循环中,脚本从文本文件中 'i' 和 'a' 之间的行中获取一定范围的文本,并检查该范围内的每一行与每一行在 ws1 中(在第二个 for 循环和 while 循环中)。 'i' 不会重置,因为它一旦增加......第二次迭代(从第一个 for 循环开始)将从新生成的 'i' 值继续,然后根据新值重置 'a' 'i' 而不是 'i' 被重置,这是因为文本文件必须完全迭代,并且这会继续通过文本文件进行。因此 'a' > 'i' 总是
    • 如果您希望根据新的“i”重置“a”,那么它需要在 for 之后但在 while 之前发生。
    猜你喜欢
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2019-11-10
    • 2020-08-14
    • 2014-03-22
    • 2021-06-29
    相关资源
    最近更新 更多