From 41ab892ee8525068dcb59eba7397662d1c447c11 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Thu, 15 Dec 2022 14:29:50 +0800 Subject: [PATCH] feat: punctuation pairs check demo --- src/punctuation/check.py | 42 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/punctuation/check.py b/src/punctuation/check.py index e87fd38..2db3e60 100755 --- a/src/punctuation/check.py +++ b/src/punctuation/check.py @@ -1,12 +1,48 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- - -target = [ +punctuationPairs = [ ('‘', '’'), ('“', '”'), ('《', '》'), ('(', ')'), ] -print(target[0]) + +def isLeftPunctuation(char: str) -> bool: + for punctuationPair in punctuationPairs: + if char == punctuationPair[0]: + return True + return False + + +def isRightPunctuation(char: str) -> bool: + for punctuationPair in punctuationPairs: + if char == punctuationPair[1]: + return True + return False + + +def getLeftPunctuation(char: str) -> str: + for punctuationPair in punctuationPairs: + if char == punctuationPair[1]: + return punctuationPair[0] + return '' # no match + + +def pairsCheck(sentence: str) -> bool: + punctuationStack = [] + sentence = list(sentence) + for i in range(0, len(sentence)): + char = sentence[i] + if isLeftPunctuation(char): + punctuationStack.append(char) + elif isRightPunctuation(char): + if punctuationStack.pop() != getLeftPunctuation(char): + return False + return len(punctuationStack) == 0 + + +print( + pairsCheck('测试“这个是OK的《2333》没错‘’”嗯嗯') +)