[英]Parsing through text file in Python and printing the line matching the String
[英]Python File Matching and Line Printing
我正在嘗試擴展以下代碼(感謝Carles Mitjans),以便如果file1和file2之間存在匹配,即file2中的12345和file1中的12345,則它將打印完整的行,包括路徑,但是在兩者之間有很多匹配項文件。
但是我似乎無法將交叉點更改為允許該交叉點的東西。
file1 example file2 example
12345 /users/test/Desktop 543252
54321 /users/test/Downloads 12345
0000 /users/test/Desktop 11111
0000
with open('Results.txt', 'r') as file1:
with open('test.txt', 'r') as file2:
a = set(x.split()[0] for x in file1)
b = [x.rstrip() for x in file2]
same = a.intersection(b)
for line in same:
print line
same.discard('\n')
當前輸出12345 0000
任何指導方針將不勝感激。
使用dict
將行映射到匹配項。 同樣,也不需要嵌套兩個循環。 可以分別計算它們,以加快處理速度。
a = set()
map = {}
with open('Results.txt', 'r') as file1:
for x in file1:
splits = x.split()
a.add(splits[0])
map[splits[0]] = x
b = []
with open('test.txt', 'r') as file2:
b = [x.rstrip() for x in file2]
same = a.intersection(b)
same.discard('\n')
for keyItem in same:
print map[keyItem]
OP注意到以上解決方案,將僅打印最后一個匹配項。 更改地圖可以解決問題。
map = dict()
with open('Results.txt', 'r') as file1:
for x in file1:
splits = x.split()
a.add(splits[0])
# If the key is not present, initialize it
if splits[0] not in map:
map[splits[0]] = []
# Append the line to map value
map[splits[0]].append(x)
其他情況將保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.