def count_conditions(input_str, listbox):
electric_attributes = ['electric', 'batter', "power"]
input_str = input_str.strip().replace('\r\n', '\n').replace('\r', '\n')
pattern = re.compile(r'(\{AND.*?\})', re.DOTALL)
matches = re.findall(pattern, input_str)
line_num = 1
for match in matches:
attrs_found = []
words = re.findall(r'\b\w+\b', match)
for word in words:
for attr in electric_attributes:
if attr in word.lower() and word not in attrs_found:
attrs_found.append(word)
if attrs_found:
message = "{} electrical attribute(s) found on lines {}-{} of AND condition: {}".format(
len(attrs_found),
line_num,
line_num + len(match.splitlines()) - 1,
', '.join(attrs_found)
)
else:
message = "No electrical attribute(s) found on lines {}-{} of AND condition".format(
line_num,
line_num + len(match.splitlines()) - 1,
)
listbox.insert("end", message)
line_num += match.count('\n') + 1
我希望代码能够确定外部的“and”语法,而不是那些已经在AND语法内部的语法。
例如,第1-14行应该被视为1 AND语法,而不是3。
{AND
condition_1:batterie
condition_2:samsung
{OR
{AND
condition_1:TV
condition_2:LCD
}
{AND
condition_1:remote
condition_2:TV
}
}
}
{AND
condition_1:batterie
condition_2:samsung
{OR
condition_3:TV
condition_4:remote
}
}
输出应为:
请帮助!我做错了什么?或者其他方法?
1条答案
按热度按时间jmo0nnb31#
我根据我的评论写了一些代码(我也对你的做了一些修改,打印这些行而不是将它们插入未知的
listbox
对象中,并将electric_attributes
更新为batterie
)。示例