![](/img/trans.png)
[英]How do I uniquely identify the content of a media file in Python, not the metadata?
[英]How do I merge multiple text file content uniquely in Python?
我有許多文本文件的文件夾,其中一些文件與其他文件的內容完全相同。 如何僅合並唯一內容並忽略重復內容? 我不刪除重復的行。 我的文件如下:
文本文件1:
Line1
Line1
Line3
文本文件2:
Line1
Line1
Line3
文本文件3:
text1
Line2
text3
結果:
Line1
Line1
Line3
text1
Line2
text3
我試過了,但這只是將所有這些合並到一個文件中:
import glob
txt_files = glob.glob('*.log')
with open('merged_files.txt','w') as merged_files:
for f in txt_files:
for line in open(f,'r'):
merged_files.write(line)
如何讀取所有文件並僅在單個文本文件中寫入唯一內容?
對於每個日志文件,計算校驗和並通過檢查校驗和是否在校驗checksums
集中來查看是否已經復制了相同的文件。 如果沒有,請將校驗和添加到集合中並復制文件,否則移至下一個文件。
import glob
import hashlib
def get_sha1(file):
checksum = hashlib.sha1()
for chunk in iter(lambda: file.read(4096), b""):
checksum.update(chunk)
return checksum.hexdigest()
def already_copied(file, checksums):
checksum = get_sha1(file)
if checksum not in checksums:
checksums.add(checksum)
return False
return True
checksums = set()
with open("merged_files.txt", "wb") as merged:
for file in glob.glob("*.log"):
with open(file, "rb") as file:
if already_copied(file, checksums):
continue
file.seek(0) # Return to the beginning of the file.
for line in file:
merged.write(line)
我們需要更多地了解您的文件。 如果文件很小,打開每個文件,將每一行放在一個數組中,使它們唯一並寫入它們。
或者您可以將每一行放在一個set
中,最后獲取值並將它們寫入文件( set
只有唯一值並且拒絕重復而不引發異常)。
但是,如果您的文件以 GB 為單位,即遠遠超過計算機的 RAM 大小,您可能需要使用 TRIE 數據結構。
試試這個代碼
import glob
unique_set = set()
txt_files = glob.glob('*.log')
for f in txt_files:
for line in open(f,'r'):
unique_set.add(line)
with open('merged_files.txt','w') as merged_files:
for line in unique_set:
merged_files.write(line)
但正如@kawadhiya21 提到的,如果您的文件遠大於計算機的 RAM 大小,則可能需要使用 TRIE 數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.