簡體   English   中英

從文本文件中創建列表並比較列表

[英]make list from text file and compare the lists

full.txt包含:

www.example.com/a.jpg
www.example.com/b.jpg
www.example.com/k.jpg
www.example.com/n.jpg
www.example.com/x.jpg

partial.txt包含:

a.jpg
k.jpg

為什么以下代碼無法提供預期的結果?

with open ('full.txt', 'r') as infile:
        lines_full=[line for line in infile]

with open ('partial.txt', 'r') as infile:
    lines_partial=[line for line in infile]    

with open ('remaining.txt', 'w') as outfile:
    for element in lines_full:
        if element[16:21] not in lines_partial: #element[16:21] means like a.jpg
            outfile.write (element)  

所需的剩余.txt應具有完全位於部分.txt中的完全.txt元素,如下所示:

www.example.com/b.jpg
www.example.com/n.jpg
www.example.com/x.jpg

此代碼將在每行末尾包含換行符,這意味着它將永遠不會與"a.jpg""k.jpg"精確匹配。

with open ('partial.txt', 'r') as infile:
    lines_partial=[line for line in infile]

更改為

with open ('partial.txt', 'r') as infile:
    lines_partial=[line[:-1] for line in infile]

刪除換行符( line[:-1]意思是“沒有該行的最后一個字符”)

您可以使用os.path庫:

from os import path

with open ('full.txt', 'r') as f:
    lines_full = f.read().splitlines()

with open ('partial.txt', 'r') as f:
    lines_partial = set(f.read().splitlines())  # create set for faster checking

lines_new = [x + '\n' for x in lines_full if path.split(x)[1] not in lines_partial]

with open('remaining.txt', 'w') as f:
    f.writelines(lines_new)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM