토큰 캡처 시퀀스 Python이 올바르게 작동하지 않음

jeff_h

내 파이썬 grepper 스크립트를 테스트하고 있습니다. 여러 검색 패턴이 필요하며 정규식 및 일반 텍스트와 잘 작동합니다.

이 테스트를 위해 input.txt에는 다음 두 줄이 있습니다.

foo blah is a bar
foo blah is bar

내가 실행하면 :

cat input.txt | ./pgreper.py "foo %{0} is a %{1}"

나는 얻어야한다 : foo blah는 출력으로 막대이지만 아무것도 얻지 못합니다.

이 분야의 도움을 주시면 대단히 감사하겠습니다.

감사 :)

추신 내 의견을 무시하십시오.

#!/usr/bin/python3

import sys
import re
import time
import datetime
import inspect
import argparse

# The following section allows arguments to be passed to the module, eg input | ./pgreper.py pattern pattern --debug
parser = argparse.ArgumentParser(description='Python Grep.')
# Enable debugging, by adding --debug at the end of command
parser.add_argument('--debug', action='store_true', help='Print debug messages')
# nargs='+', enables multiple patterns to be entered at the commandline eg input | ./pgreper.py pattern pattern
parser.add_argument('pattern', type=str, nargs='+', help='Pattern(s) for pgrepping')
args = parser.parse_args()


# This is the class that allows for debugging a line in sys.stdin, if it matches all patterns.
class CodeTrace(object):
    def __init__(self, line, pattern):
        self.line = line
        self.pattern = pattern

    # @staticmethod
    # This is the degugging method
    def trace(self, line, pattern):
        # Capture the current time, and format the timestamp, into a readable format
        ts = datetime.datetime.fromtimestamp(time.time()).strftime('[%Y-%m-%d %H:%M:%S:%f]')
        # Inspect allows us to blah, inspecting the stack allows us to retrieve information
        stack = inspect.stack()
        # Retrieve calling class information
        the_class = stack[1][0].f_locals["self"].__class__
        # Retrieves the calling method information
        the_method = stack[1][0].f_code.co_name
        # Retrieves the calling method's variables
        the_variables = stack[1][0].f_code.co_varnames
        # Formats the contents of the debug trace into a readable format,
        # Any parameters passed to the method and the return value, are included in the debug trace
        debug_trace = ("{} {}.{}.{} {} {} ".format(ts, str(the_class), the_method,the_variables, pattern, line))
        # Send out the debug trace as a standard error output
        sys.stderr.write(debug_trace + "\n")


# This is the class that does the pattern matching
class Grepper(object):
    def __init__(self, patterns, debug=False):
        # Every pattern that this module takes is compiled here, so that it may be searched for in sys.stdin
        self.patterns = [re.compile(p) for p in patterns]
        self.debug = debug

    # This method compares the input, to the patterns compiled in Grepper
    def matchline(self, debug):
        for line in sys.stdin:
            # This line compares all the patterns to the input, only if the input matches ALL patterns does it pass
            if all(p.search(line) for p in self.patterns):
                sys.stdout.write(line)
                # this if statement runs the CodeTrace.trace function, if the user adds the --debug option in the cli
                if self.debug:
                    CodeTrace(line, self.patterns).trace(line, args.pattern)


# This main function calls the grepper class and the matchline method, for the purpose of pattern matching
def main():
    print(args.pattern)
    Grepper(args.pattern, args.debug).matchline(args.debug)

# This allows the module to be used as a standalone module, or a reusable module in a different program
if __name__ == "__main__":
    main()
Aran-Fey

현재 명령 줄 인수를 자리 표시 자 %{0}을 바꾸지 않고 정규식 패턴으로 해석 하고 %{1}있습니다. 자리 표시자를 .*다음과 같이 또는 이와 유사한 것으로 바꾸고 싶을 것입니다 .

class Grepper(object):
    def __init__(self, patterns, debug=False):
        patterns= [re.sub(r'%\{\d\}', '.*', p) for p in patterns]
        self.patterns = [re.compile(p) for p in patterns]

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

토큰 캡처 시퀀스 Python이 올바르게 작동하지 않음

분류에서Dev

텍스처 이미지가 올바르게 표시되지 않음-OpenGL

분류에서Dev

예기치 않은 토큰`fi '근처의 구문 오류 | 형식이 올바르게 표시됨

분류에서Dev

ios7 상태 표시 줄이 올바르게 작동하지 않음

분류에서Dev

스왑 드라이브가 올바르게 작동하지 않음

분류에서Dev

부트 스트랩 템플릿이 올바르게 작동하지 않음 Django

분류에서Dev

각도 및 laravel 무한 스크롤이 올바르게 작동하지 않음

분류에서Dev

Vuex 스토어 / 내비게이션 가드가 처음 작동하지 않음

분류에서Dev

OpenGL을 사용하면 텍스처 매핑이 올바르게 작동하지 않습니다.

분류에서Dev

Python Auto ARIMA 모델이 올바르게 작동하지 않음

분류에서Dev

Rmarkdown 그림 캡션이 올바르게 인쇄되지 않음

분류에서Dev

Python TKinter 진행률 표시 줄 레이블이 올바르게 작동하지 않음

분류에서Dev

Python 형식이 올바르게 표시되지 않음

분류에서Dev

Unity Slerp Rotation이 원래 회전으로 다시 이동 됨-음수로 올바르게 작동하지 않음

분류에서Dev

Apache URL 재 작성이 올바르게 작동하지 않음

분류에서Dev

CodeIgniter 검색 엔진이 올바르게 작동하지 않음-게시 된 게시물 만 가져 오기

분류에서Dev

데이터 노드가 올바르게 시작되지 않음

분류에서Dev

RewriteRule이 올바르게 다시 작성되지 않음

분류에서Dev

MacOS catalina Makefile이 CLI에서 작동하는 쉘 명령을 올바르게 처리하지 않음

분류에서Dev

imshow ()가 이미지를 올바르게 표시하지 않음

분류에서Dev

UIPickerView가 이미지를 올바르게 표시하지 않음

분류에서Dev

Python Args가 올바르게 작동하지 않음

분류에서Dev

Postgresql이 시간대를 올바르게 변환하지 않음

분류에서Dev

JLabel이 HTML을 올바르게 표시하지 않음

분류에서Dev

Ansible : delegate_to 그룹이 올바르게 작동하지 않음

분류에서Dev

부울이 올바르게 작동하지 않음

분류에서Dev

Hibernate Crtieria 및 제한이 올바르게 작동하지 않음

분류에서Dev

HTML 선택이 올바르게 작동하지 않음

분류에서Dev

Javascript setInterval if 문이 올바르게 작동하지 않음

Related 관련 기사

  1. 1

    토큰 캡처 시퀀스 Python이 올바르게 작동하지 않음

  2. 2

    텍스처 이미지가 올바르게 표시되지 않음-OpenGL

  3. 3

    예기치 않은 토큰`fi '근처의 구문 오류 | 형식이 올바르게 표시됨

  4. 4

    ios7 상태 표시 줄이 올바르게 작동하지 않음

  5. 5

    스왑 드라이브가 올바르게 작동하지 않음

  6. 6

    부트 스트랩 템플릿이 올바르게 작동하지 않음 Django

  7. 7

    각도 및 laravel 무한 스크롤이 올바르게 작동하지 않음

  8. 8

    Vuex 스토어 / 내비게이션 가드가 처음 작동하지 않음

  9. 9

    OpenGL을 사용하면 텍스처 매핑이 올바르게 작동하지 않습니다.

  10. 10

    Python Auto ARIMA 모델이 올바르게 작동하지 않음

  11. 11

    Rmarkdown 그림 캡션이 올바르게 인쇄되지 않음

  12. 12

    Python TKinter 진행률 표시 줄 레이블이 올바르게 작동하지 않음

  13. 13

    Python 형식이 올바르게 표시되지 않음

  14. 14

    Unity Slerp Rotation이 원래 회전으로 다시 이동 됨-음수로 올바르게 작동하지 않음

  15. 15

    Apache URL 재 작성이 올바르게 작동하지 않음

  16. 16

    CodeIgniter 검색 엔진이 올바르게 작동하지 않음-게시 된 게시물 만 가져 오기

  17. 17

    데이터 노드가 올바르게 시작되지 않음

  18. 18

    RewriteRule이 올바르게 다시 작성되지 않음

  19. 19

    MacOS catalina Makefile이 CLI에서 작동하는 쉘 명령을 올바르게 처리하지 않음

  20. 20

    imshow ()가 이미지를 올바르게 표시하지 않음

  21. 21

    UIPickerView가 이미지를 올바르게 표시하지 않음

  22. 22

    Python Args가 올바르게 작동하지 않음

  23. 23

    Postgresql이 시간대를 올바르게 변환하지 않음

  24. 24

    JLabel이 HTML을 올바르게 표시하지 않음

  25. 25

    Ansible : delegate_to 그룹이 올바르게 작동하지 않음

  26. 26

    부울이 올바르게 작동하지 않음

  27. 27

    Hibernate Crtieria 및 제한이 올바르게 작동하지 않음

  28. 28

    HTML 선택이 올바르게 작동하지 않음

  29. 29

    Javascript setInterval if 문이 올바르게 작동하지 않음

뜨겁다태그

보관