[英]Diff and intersection reporting between two text files
免責聲明:我是編程和腳本的新手,所以請原諒缺乏技術術語
所以我有兩個包含列出的名稱的文本文件數據集:
First File | Second File
bob | bob
mark | mark
larry | bruce
tom | tom
我想運行一個腳本(pref python),輸出一個文本文件中的相交線和另一個文本文件中的不同行,例如:
匹配.txt :
bob
mark
tom
差異.txt :
bruce
我將如何使用 Python 完成此任務? 或者使用 Unix 命令行,如果它足夠簡單?
排序 | uniq 很好,但 comm 可能更好。 “man comm”了解更多信息。
從手冊頁:
EXAMPLES
comm -12 file1 file2
Print only lines present in both file1 and file2.
comm -3 file1 file2
Print lines in file1 not in file2, and vice versa.
您也可以使用 Python 集類型,但 comm 更容易。
Unix shell 解決方案-:
# duplicate lines
sort text1.txt text2.txt | uniq -d
# unique lines
sort text1.txt text2.txt | uniq -u
words1 = set(open("some1.txt").read().split())
words2 = set(open("some2.txt").read().split())
duplicates = words1.intersection(words2)
uniques = words1.difference(words2).union(words2.difference(words1))
print "Duplicates(%d):%s"%(len(duplicates),duplicates)
print "\nUniques(%d):%s"%(len(uniques),uniques)
至少是這樣的
Python 字典是 O(1) 或非常接近,換句話說,它們非常快(但如果您索引的文件很大,它們會使用大量內存)。 所以首先讀入第一個文件並構建一個字典,如下所示:
left = [x.strip() for x in open('left.txt').readlines()]
列表理解和 strip() 是必需的,因為 readlines 為您提供帶有完整尾隨換行符的行。 這將創建文件中所有項目的列表,假設每行一個(如果它們都在一行上,則使用 .split)。
現在建立一個字典:
ldi = dict.fromkeys(left)
這將構建一個以列表中的項目為鍵的字典。 這也處理重復。 現在遍歷第二個文件並檢查鍵是否在字典中:
matches = open('matches.txt', 'w')
uniq = open('uniq.txt', 'w')
for l in open('right.txt').readlines():
if l.strip() in ldi:
# write to matches
matches.write(l)
else:
# write to uniq
uniq.write(l)
matches.close()
uniq.close()
>>> with open('first.txt') as f1, open('second.txt') as f2:
w1 = set(f1)
w2 = set(f2)
>>> with open('matches.txt','w') as fout1, open('differences.txt','w') as fout2:
fout1.writelines(w1 & w2)
fout2.writelines(w2 - w1)
>>> with open('matches.txt') as f:
print f.read()
bob
mark
tom
>>> with open('differences.txt') as f:
print f.read()
bruce
用水平線制作一個;
file_1_list = []
with open(input('Enter the first file name: ')) as file:
file_1 = file.read()
file.seek(0)
lines = file.readlines()
for line in lines:
line = line.strip()
file_1_list.append(line)
with open(input('Enter the second file name: ')) as file:
file_2 = file.read()
file.seek(0)
lines = file.readlines()
for line in lines:
line = line.strip()
if file_1 == file_2:
print("Yes")
else:
print("No")
print(file_1)
print("--------------")
print(file_2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.