【问题标题】:make list from text file and compare the lists从文本文件制作列表并比较列表
【发布时间】:2013-09-17 17:22:27
【问题描述】:

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 应具有 full.txt 中不在 partial.txt 中的那些元素,如下所示:

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

【问题讨论】:

  • 你试过打印lines_full和lines_partial吗?结果如何?

标签: python


【解决方案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)

【讨论】:

【解决方案2】:

此代码将在每行末尾包含换行符,这意味着它永远不会精确匹配 "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] 表示“没有行的最后一个字符”)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多