假设我们被赋予角色'。'要确定它是否在字符之间('和')',如何在不使用re(正则表达式)模块的情况下完成此操作?
非常感谢任何帮助或提示! 干杯!
答案 0 :(得分:2)
基本想法,找到一个.
字符,然后在左边找到打开的parens,在右边找到关闭的parens。
def dot_inside_parens(s):
for i, c in enumerate(s):
if c == '.':
return '(' in s[:i] and ')' in s[i+1:]
>>> dot_inside_parens('((.)')
True
>>> dot_inside_parens('.((.)')
True
>>> dot_inside_parens('.(()')
False
这并未考虑到平衡,例如:
>>> dot_inside_parens('(.()')
True
因为在两个括号中有一个点。
为了解决这个未来,您可以使用更复杂的算法。基本上找一个.
字符,找到后,向左看 non closed paren ,然后向右看 non opened paren 。如果你找到两者,则.
被正确地包含在parens之间。
def dot_inside_parens2(s):
found = False
for i, c in enumerate(s):
if c == '.':
aux = 0
for c1 in s[:i][::-1]: # iterate over the remaining string to the left
if c1 == '(':
aux += 1
if aux > 0:
break
elif c1 == ')':
aux -= 1
if aux > 0:
found = True # no opened parens to the left
aux = 0
for c1 in s[i+1:]: # iterate over the remaining string to the right
if c1 == ')':
aux += 1
if aux > 0:
break
elif c1 == '(':
aux -= 1
if aux > 0 and found:
return True # no closed parens to the right
return False
>>> dot_inside_parens2('(edge.).(case)')
True
>>> dot_inside_parens2('(edge).(case)')
False
>>> dot_inside_parens2('(.()')
False
>>> dot_inside_parens2('((.)')
True
希望这有帮助!
答案 1 :(得分:0)
嗯,我想到了一个非常简单的实现。从:
开始string_list = initial_string.split(".")
这会产生一个字符串列表,其中每个字符串之间的边界是"。"。在简单的情况下,只有一个"。"在字符串中,我们只需要查看"("是否在string_list [0]中以及")"在string_list [1]中。或者换句话说
(string_list[0].find("(") + 1) and (string_list[1].find(")") + 1)
' + 1'因为string.find()返回匹配的最低索引,所以如果字符串是例如"(",然后find将返回0,0 == False。
对于更复杂的解析,我们需要更多的继续...应该"(..)"回归真的吗?应该"。(。)"回归真的吗?应该")(。)"回归真的吗?应该"()。)"回归真的吗?上述过程可以扩展到处理这些情况,但列出每个案例的所有可能的实现将占用大量的空间和时间。
答案 2 :(得分:-1)
嗯,这是我写过的最丑陋的黑客。
depth = 0
for i,character in enumerate(mystring):
if character == "(": depth += 1
elif character == ")": depth -= 1
# you may want to ignore any closing parens with no open parens, in
# which case you'd do depth = max(0, depth-1)
elif character == '.' and depth > 0 and ")" in mystring[i+1:]:
# this period is between parens