我有2個記錄在檔案中的串列(File1.txt和File2.txt),我需要逐行比較,并在Output.txt檔案中記錄相同出現的數量。
然而,寫入輸出的結果是不正確的。請看下面我使用的代碼,以及獲得的結果和想要的結果:
input_file1 = open('C:TempFile1.txt', 'r')
input_file2 = open('C:TempFile2.txt', 'r')
output_file = open('C:TempOutput.txt','w')
match = 0
strOutput = ""/span>
for line1 in input_file1:
LST1 = list(line1)
input_file2.seek(0)
output_file.write('
')
for line2 in input_file2:
LST2 = list(line2)
match = len(set(LST1) .intersection(set(LST2))
strOutput = str(match) ', ' line2
output_file.write("%s"/span>%(strOutput))
output_file.close()
input_file2.close()
input_file1.close()
input_file1:
01,04,07,23,39
03,05,08,37,45[br>
02,03,10,13,28
input_file2:
01,02,03,21,22,23,27
03,05,10,13,37,39,47
輸出(INCORRECT!):
7,01,02,03,21,22,23,27
7,03,05,10,13,37,39,47
5,01,02,03,21,22,23,27
6,03,05,10,13,37,39,47
5,01,02,03,21,22,23,27
4,03,05,10,13,37,39,47
輸出(正確的):
2,01,02,03,21,22,23,27
1,03,05,10,13,37,39,47
1,01,02,03,21,22,23,27
3,03,05,10,13,37,39,47
2,01,02,03,21,22,23,27
3,03,05,10,13,37,39,47
OR:
輸出(正確的):
2,1,2,3,21,22,23,27
1,3,5,10,13,37,39,47
1,1,2,3,21,22,23,27
3,3,5,10,13,37,39,47
2,1,2,3,21,22,23,27
3,3,5,10,13,37,39,47
uj5u.com熱心網友回復:
這里是固定的代碼:
input_file1 = open('File1.txt'/span>, 'r'/span>)
input_file2 = open('File2.txt', 'r')
output_file = open('output.txt','w')
match = 0
strOutput = ""/span>
for line1 in input_file1:
LST1 = line1.strip().split(' ,')
input_file2.seek(0)
output_file.write('
')
for line2 in input_file2:
LST2 = line2.strip().split(', ')
match = len(set(LST1) .intersection(set(LST2))
strOutput = str(match) ', ' line2
output_file.write("%s"/span>%(strOutput))
output_file.close()
input_file2.close()
input_file1.close()
主要有兩個問題:
1.
1- 原始行。LST1 = list(line1)并沒有生成正確的串列,最后生成了一個串列。['0', '1', ',' , '0', ....]而不是['01', '02',...]
2- 在你的原始檔案中,你在每一行的末尾都有一個新的行字符,因此你的第一行看起來像這樣。'01,04,07,23,39
'通過這兩個改動,你最終得到了這一行:
LST1 = line1.strip().split(' ,')
其中.strip()洗掉了新的行字符,而.split(',')將其正確分割。
運行該代碼后,我得到了這樣的輸出:
2,01,02,03。 21,22,23,27。
1,03,05,10,13,37,39,47。
1,01,02,03,21,22,23,27.
3,03,05,10,13,37,39,47。
2,01,02,03,21,22,23,27.
3,03,05,10,13,37,39,47.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/308543.html
標籤:
