0

我是 python 新手,我试图匹配我从两个 .txt 中提取的数据,如果每个文件的每一行的第一个元素与每个文件的每一行的第一个元素重合,它应该给出一个输出这将把该信息写在excel表上。到目前为止,这就是我所得到的,但我被阻止了,所以我将不胜感激。我只是使用 for 循环进行迭代,所以我不知道该怎么做,以便我可以在两个文件之间进行比较,以及是否有匹配项以在没有 for 循环的情况下编写它

import xlwt
c1=-1
c2=0

file1=open('/Users/whatever.txt','r')
file2=open('/Users/whatever2.txt','r')

style0=xlwt.easyxf('font:name Times New Roman,colour black,bold on')
wb=xlwt.Workbook()

ws=wb.add_sheet('x',cell_overwrite_ok=True)

ws2=wb.add_sheet('y',cell_overwrite_ok=True)
row=0
row2=0

for lineA in file1:

    split=lineA.split('\t')
    split.pop(5)
    split.pop(5)
    split.pop(6)
    split.pop(6)
    split.pop(6)
    split.pop(6)
    split.pop(7)
    split.pop(7)
    split.pop(7)
    if '123\n'in split:
        continue
    elif '567\n' in split:
        continue
    elif '8910\n' in split:
        continue
    else:
        ws.write(0,0,euk,style0)
        ws.write(row,0,str(c1),style0)
        ws.write(row,1,split[0],style0)
        ws.write(row,2,split[1],style0)
        ws.write(row,3,split[2],style0)
        ws.write(row,4,split[3],style0)
        ws.write(row,5,split[4],style0)
        ws.write(row,6,split[5],style0)
        ws.write(row,7,split[6],style0)
        ws.write(row,8,split[7],style0)

        row+=1

for lineB in file2:

    split1=lineB.split('\t')
    split1.pop(5)
    split1.pop(5)
    split1.pop(5)
    split1.pop(5)
    split1.pop(5)
    split1.pop(5)
    split1.pop(5)
    split1.pop(-2)
    split1.pop(-2)
    split1.pop(-2)


  if '654\n' in split1:

        ws2.write(0,0,prok,style0)
        ws2.write(row2,0,str(c2),style0)
        ws2.write(row2,1,split1[0],style0)
        ws2.write(row2,2,split1[1],style0)
        ws2.write(row2,3,split1[2],style0)
        ws2.write(row2,4,split1[3],style0)
        ws2.write(row2,5,split1[4],style0)
        ws2.write(row2,6,split1[5],style0)
        ws2.write(row2,7,split1[6],style0)
        #print(split1)
        c2=c2+1
        row2+=1

wb.save('Hello.xls')
4

1 回答 1

0

我想我遵循您正在尝试做的事情。比较每一行的第一个元素应该不会太难。尝试以下操作:

file1=open('/Users/whatever.txt','r')
file2=open('/Users/whatever2.txt','r')

for line in file1.readlines():
    # Split the line by tab spaces
    split_line = line.split('/t')
    # get the first element
    l1 = split_line[0]
    # Split the first line of file2 by tab spaces
    split_line2 = file2.readline().split("/t")
    # Get the first element of the file2 split line
    l2 = split_line2[0]

    # Check if they match
    if l1 == l2:
        # If they match, add it to your file
        # Add your write code here
    # If they don't match, nothing will be written

以下应该做同样的事情,但更简洁:

for line in file1.readlines():
    if line.split("/t")[0] == file2.readline().split("/t")[0]:
        # Add your write code here
于 2012-07-19T17:45:47.623 回答