繁体   English   中英

使用python从另一个文件中的一个文件中grep行

[英]Use python to grep lines from one file out of another file

类似的问题替代python中的“grep”; 但这里的复杂性是grepped来自另一个文件的变量(行)。 我无法弄清楚如何使用re.findall()等函数来做到这一点

文件1:

1  20  200
1  30  300

文件2:

1  20  200  0.1  0.5
1  20  200  0.3  0.1
1  30  300  0.2  0.6
1  40  400  0.9  0.6
2  50  300  0.5  0.7

file1中的每一行都是我的模式; 我需要从file2中搜索这样的模式。 那么结果应该是:

    1  20  200  0.1  0.5
    1  20  200  0.3  0.1
    1  30  300  0.2  0.6

我一直在尝试使用bash或python解决问题,但无法搞清楚。 谢谢

这是一个非正则表达式的解决方案:

with open('/tmp/file1') as f:
  lines1 = f.readlines()

with open('/tmp/file2') as f:
  for line in f:
    if any(line.startswith(x.strip()) for x in lines1):
      print line,

你可以利用|的事实 正则表达式中的字符表示匹配左侧的模式或右侧的模式:

import re

with open('file1') as file1:
    patterns = "|".join(re.escape(line.rstrip()) for line in file1)

regexp = re.compile(patterns)
with open('file2') as file2:
    for line in file2:
        if regexp.search(line):
            print line.rstrip()

当我在您的示例文件上尝试此操作时,它输出:

1   20  200 0.1 0.5
1   20  200 0.3 0.1
1   30  300 0.2 0.6

顺便说一下,如果你想在bash中解决这个问题,下面应该这样做:

grep -f file1 file2 

我想你需要自己的循环

file1patterns = [ re.Pattern(l) for l in f1.readlines() ]
lineToMatch = 0
matchedLines = []
for line in f2.readlines():
  if file1patterns[lineToMatch].matches(line):
    matchedLines += line
    lineToMatch += 1
  else:
    lineToMatch = 0
    matchedLines = []
  if len(matchedLines) == len(file1patterns)
    print matchedLines
    lineToMatch = 0
    matchedLines = []

(不是实际编译Python,但希望你能继续前进)

步骤1:读入文件1中的所有行,拆分它们并将它们作为元组添加到集合中。 这将有助于我们在下一步中更快地进行查找。

with open('file1', 'r') as f:
    file1_lines = set([tuple(line.strip().split()) for line in f])

第2步:从file2过滤符合条件的行,即如果它们以file1中的任何行开头:

with open('file2', 'r') as f2:
    for line in itertools.ifilter(lambda x: tuple(x.split()[:3]) in file1_lines, f2):
        print line

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM