[英]Copy N lines from File1 to File2, then delete copied lines in File1
[英]Test if the lines in file1 are a subset of the lines in file2
我嘗試過在線搜索答案,但不幸的是沒有成功。 因此,我在這里問:
我想弄清楚如果所有線條file1
存在於file2
。 幸運的是,我只能比較整行而不是單個單詞等。不幸的是,我正在處理GB文件,因此我嘗試的一些基本解決方案給了我內存錯誤。
目前,我有下面的代碼不起作用。 一些指導將不勝感激。
# Checks if all lines in file1 are present in file2
def isFile1SubsetOfFile2(file1 , file2):
file1 = open(file1, "r")
for line1 in file1:
with open(file2, "r+b") as f:
mm=mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
my_str_as_bytes = str.encode(line1)
result = mm.find(line1.strip().encode())
print(result)
if result == -1:
return False
return True
樣本文件2:
This is line1.
This is line2.
This is line3.
This is line4.
This is line5.
This is line6.
This is line7.
This is line8.
This is line9.
如果例如file1為:
This is line4.
This is line5.
如果例如file1是,則應該失敗:
This is line4.
This is line10.
編輯:我剛剛添加了我的代碼的工作版本,以使他人受益。 沒有內存錯誤,但是非常慢。
我不確定為什么它不起作用,但是我想我知道一種解決問題的方法:
def is_subset_of(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
for line in f1:
line = line.strip()
f2.seek(0) # go to the start of f2
if line not in (line2.strip() for line2 in f2):
return False
return True
通過始終為每一行尋找新的開始,這樣避免了多次打開第二個文件,並且在任何時候您只在內存中保留2行。 那應該對內存非常友好。
另一種方法(可能更快)是對file1
和file2
進行排序。 這樣,如果字符串在詞法上小於第一個文件中的字符串,則可以逐行比較並移至另一個文件中的下一行。 代替O(n**2)
可以在O(n*log(n))
。 但是,這要復雜得多,我不知道對GB的文件進行排序是否有意義(可能使用過多的內存!)。
處理不適合內存的文件總是很困難。
如果file1
容納在內存中,但是file2
太大,則可以采用以下解決方案:
# file1 and file2 are open file-like objects
unseen = set(file1)
for line in file2:
unseen -= {line} # avoid exception from set.remove
#if unseen is empty, all lines were found in file2
否則,您應該對至少一個文件進行排序(或按CFBS排序)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.