【问题标题】:Python: Use value from file a to search for lines in another filePython:使用文件a中的值来搜索另一个文件中的行
【发布时间】:2012-12-25 18:56:45
【问题描述】:

新手问题

我有 2 个文件 文件 A:包含项目列表的文件(苹果、梨、橙子) 文件 B:世界上所有水果的文件(1,000,000 行)

在 unix 中,我会从文件 B 中 grep apple 并返回所有结果

在 unix 中我会 1. grep apple 从文件 b >>fruitfound.txt 2. grep pears from file b >> fruitfound.txt 3. grep 文件 b 中的橙子 >>fruitfound.txt

我想要一个 python 脚本,它使用文件 a 和搜索文件 b 中的值,然后写出输出。注意:文件 B 会有青苹果、红苹果、黄苹果,我想将所有 3 个结果写入fruitfound.txt

最诚挚的问候

科尼蒂

【问题讨论】:

  • 尊敬的用户,欢迎来到 SO。说明您已经尝试过什么以及问题所在,我们将尽最大努力帮助您。
  • 您可以将 grep 命令合并为一个:grep -f a b > fruitfound.txt

标签: python file search


【解决方案1】:

grep -f $patterns $filename 正是这样做的。无需使用 python 脚本。

【讨论】:

    【解决方案2】:

    要在 Python 中查找包含任何给定关键字的行,您可以使用正则表达式:

    import re
    from itertools import ifilter
    
    def fgrep(words, lines):
        # note: allow a partial match e.g., 'b c' matches 'ab cd'
        return ifilter(re.compile("|".join(map(re.escape, words))).search, lines)
    

    将其转换为命令行脚本:

    import sys
    
    def main():
        with open(sys.argv[1]) as kwfile: # read keywords from given file
            # one keyword per line
            keywords = [line.strip() for line in kwfile if line.strip()]
    
        if not keywords:
           sys.exit("no keywords are given")
    
        if len(sys.argv) > 2: # read lines to match from given file
            with open(sys.argv[2]) as file:
                sys.stdout.writelines(fgrep(keywords, file))
        else: # read lines from stdin
            sys.stdout.writelines(fgrep(keywords, sys.stdin))
    
    main()
    

    例子:

    $ python fgrep.py a b > fruitfound.txt
    

    有更有效的算法,例如Ago-Corasick algorithm,但在我的机器上过滤数百万行只需要不到一秒钟的时间,它可能已经足够好了(grep 快几倍)。令人惊讶的是,基于 Ago-Corasick 算法的 acora 对于我尝试过的数据来说速度较慢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多