我想在python中的大文件中過濾重疊行。如何在python中過濾大文件中兩行的重疊
重疊度設置爲兩行和另外兩行的25%。換言之,重疊度是a*b/(c+d-a*b)>0.25
,a
是第1行和第3行之間的交叉的數目,b
是的第二行和第四行之間的交叉的數目,c
是元件的數量第一行乘以第二行的元素數,d
是第三行的元素數乘以第四行的元素數。如果重疊度大於0.25,則刪除第3行和第4行。所以,如果我有總共1000個000行的大文件,第6行如下:
C6 C24 C32 C54 C67
K6 K12 K33 K63 K62
C6 C24 C32 C51 C68 C78
K6 K12 K24 K63
C6 C32 C24 C63 C67 C54 C75
K6 K12 K33 K63
由於重疊度第一兩行和第二行的是a=3
,(如c6,c24,c32
),b=3
(例如k6,k12,k63
),c=25,d=24
,a*b/(c+d-a*b)=9/40<0.25
,第3行和第4行不被刪除。接下來,前兩行和第三兩行的重疊度爲5*4/(25+28-5*4)=0.61>0.25
,第三兩行被刪除。
最終答案是第1和第2兩行。
C6 C24 C32 C54 C67
K6 K12 K33 K63 K62
C6 C24 C32 C51 C68 C78
K6 K12 K24 K63
的僞代碼如下:
for i=1:(n-1) # n is a half of the number of rows of the big file for j=(i+1):n if overlap degrees of the ith two rows and jth two rows is more than 0.25 delete the jth two rows from the big file end end end
python代碼如下,但它是錯誤的。如何解決它?
with open("iuputfile.txt") as fileobj: sets = [set(line.split()) for line in fileobj] for first_index in range(len(sets) - 4, -2, -2): c=len(sets[first_index])*len(sets[first_index+1]) for second_index in range(len(sets)-2 , first_index, -2): d=len(sets[second_index])*len(sets[second_index+1]) ab = len(sets[first_index] | sets[second_index])*len(sets[first_index+1] | sets[second_index+1]) if (ab/(c+d-ab))>0.25: del sets[second_index] del sets[second_index+1] with open("outputfile.txt", "w") as fileobj: for set_ in sets: # order of the set is undefined, so we need to sort each set output = " ".join(set_) fileobj.write("{0}\n".format(output))
類似的問題可以在https://stackoverflow.com/questions/17321275/
找到如何修改這些代碼在Python來解決這個問題?謝謝!
_」c是第二行「_實際上不清楚的第一行的次數。我猜c是通過乘以兩行元素的數量來計算的,但是這與你的第二個例子'c = 55'不符。你還有什麼嘗試,因爲你已經有工作代碼,從開始? – Pierre
@Pierre我再次檢查問題,修復了錯誤並添加了一些解釋。 – user2405694