简体   繁体   English

python 中的简化 grep

[英]Simplified grep in python

I need to create a simplified version of grep in python which will print a line when a keyword is used such as using this command "python mygrep.py duck animals.txt" and getting the output, "The duck goes quack".我需要在 python 中创建 grep 的简化版本,它会在使用关键字时打印一行,例如使用此命令“python mygrep.py duck animals.txt”并获取 Z78E6221F6393D13566681DB398F14CE。 I have a file where it contains different outputs but I'm not sure how to get it to print the line that contains the "keyword" such as the line with "duck" in it.我有一个文件,其中包含不同的输出,但我不确定如何让它打印包含“关键字”的行,例如其中包含“duck”的行。 Im suppose to only use "import sys" and not "re" since its suppose to be a simple version.我想只使用“import sys”而不是“re”,因为它假设是一个简单的版本。

import sys

def main():
    if len(sys.argv) != 3:
        exit('Please pass 2 arguments.')

    search_text = sys.argv[1]
    filename = sys.argv[2]

    with open("animals.txt", 'r') as f:
       text = f.read()
    for line in text:
        print(line)


if __name__ == '__main__':
    main()

The operator 'in' should be sufficient.运算符“in”应该足够了。

for line in text:
    if search_text in line:
        print(line)

Here is a an implementation of grep in python with after/before feature:这是 python 中 grep 的实现,具有后/前功能:

    def _fetch_logs(self, data, log_file, max_result_size, current_result_size):
        after = data.get("after", 0)
        before = data.get("before", 0)
        exceeded_max = False
        result = []
        before_counter = 0
        frame = []
        found = False
        for line in log_file:
            frame.append(line)
            match_patterns = all(self._search_in(data, pattern, line) for pattern in data["patterns"])
            if match_patterns:
                before_counter = len(frame)
                found = True

            if not found and len(frame) > before:
                frame.pop(0)

            if found and len(frame) >= before_counter + after:
                found = False
                before_counter = 0
                result += frame
                frame = []

            if current_result_size + len(result) >= max_result_size:
                exceeded_max = True
                break
        if found:
            result += frame
        return exceeded_max, result

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

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