【问题标题】:Python remove file lines without matches from another filePython从另一个文件中删除不匹配的文件行
【发布时间】:2016-07-08 00:38:52
【问题描述】:

我有两个文件,第一个包含必要数据:1st file,第二个包含要保留的行列表:2nd file

我尝试通过python代码进行过滤:

import os.path

# loading the input files
output    = open('descmat.txt', 'w+')
input     = open('descmat_all.txt', 'r')
lists      = open('training_lines.txt', 'r')
print "Test1"

# reading the input files
list_lines = lists.readlines()
list_input = input.readlines()

print "Test2"
output.write(list_input[0])

for i  in range(len(list_lines)):
    for ii in range(len(list_input)):
        position = list_input[ii].find(list_lines[i][:-1])
        if position > -1:
            output.write(list_input[ii])
        break 

print "Test3"
output.close()

但此脚本找不到任何匹配项。仅保留第一个文件中与第二个文件匹配的行的最简单解决方案是什么?

【问题讨论】:

    标签: python string text match string-matching


    【解决方案1】:

    替换这部分代码:

    for i  in range(len(list_lines)):
        for ii in range(len(list_input)):
            position = list_input[ii].find(list_lines[i][:-1])
            if position > -1:
                output.write(list_input[ii])
            break 
    

    通过这个:

    for i  in range(len(list_lines)):
        for ii in range(len(list_input)):
            if list_input[ii][:26] == list_lines[i][:-1]:
                output.write(list_input[ii])
    

    正是我需要的。

    【讨论】:

      【解决方案2】:

      如果您将文件都读入一个列表,您可以简单地比较这些列表。看看here 怎么做。 out 应该包含一个可以匹配的字符串列表。

      out = [e for e in list_input for i in list_lines if e.startswith(i)]
      output.writelines(out)
      

      【讨论】:

      • 好的,我之前没有检查你的文件。据我了解您的文件,您必须匹配每个字符串的开始序列。我已经稍微改变了我的代码。检查它是否有效。
      • 谢谢!我找到了有效的解决方案;我仍然不明白为什么这段代码不起作用...
      • 抱歉,我编辑的代码只是几秒钟前才出现的。但是,我用你文件的前两行检查了我的新代码,它可以工作。
      • 你有 Python 2.8 吗?仍然不适合我...很奇怪,所以我将继续使用简单的“如果”解决方案。
      • 有趣,我正在使用 Python 3.5,但功能是基本的 Python。 out 列表是空的还是只有输出文件?实际上,此代码与您的 if 解决方案完全相同。列表比较中的嵌套循环。
      【解决方案3】:

      对于这类问题,Python 有set 数据类型

      # prepare a set of normalised training lines
      # stripping new lines avoids possible problems with the last line
      
      OK_lines = set(line.rstrip('\n') for line in open('training_lines.txt'))
      
      # when you leave a with block, all the resources are released
      # i.e., no need for file.close()
      
      with open('descmat_all.txt') as infile:
          with open('descmat.txt', 'w') as outfile:
              for line in infile:
                  # OK_lines have been stripped, input lines must be stripped as well
                  if line.rstrip('\n') in OK_lines:
                      outfile.write(line)
      

      一个简单的测试

      boffi@debian:~/Documents/tmp$ cat check.py 
      # prepare a set of normalised training lines
      # stripping new lines avoids possible problems with the last line
      
      OK_lines = set(line.rstrip('\n') for line in open('training_lines.txt'))
      
      # when you leave a with block, all the resources are released
      # i.e., no need for file.close()
      
      with open('descmat_all.txt') as infile:
          with open('descmat.txt', 'w') as outfile:
              for line in infile:
                  # OK_lines have been stripped, input lines must be stripped as well
                  if line.rstrip('\n') in OK_lines:
                      outfile.write(line)
      
      boffi@debian:~/Documents/tmp$ cat training_lines.txt 
      ada
      bob
      boffi@debian:~/Documents/tmp$ cat descmat_all.txt 
      bob
      doug
      ada
      doug
      eddy
      ada
      bob
      boffi@debian:~/Documents/tmp$ python check.py
      boffi@debian:~/Documents/tmp$ cat descmat.txt 
      bob
      ada
      ada
      bob
      boffi@debian:~/Documents/tmp$ 
      

      【讨论】:

      • 作为输出只有空文件
      • 它适用于我,请参阅我添加到帖子中的测试用例。
      • 感谢您的解释,但有我的输入文件:pastebin.com/PTEm2Trppastebin.com/3MUAQzaQ - 运行此代码会生成一个 emty 文件...
      • 如果 A 的行恰好是 B 中包含的一行,我的代码将一行从 A 复制到 C。也许我误解了你想要的,也许你的输入文件中没有行与任何行完全匹配在您的培训文件中。 ---如果是我的误解,你可以把你的Q说得更清楚,我可以尝试给出另一个答案。
      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2011-09-25
      • 2012-08-14
      • 2012-07-07
      相关资源
      最近更新 更多