![](/img/trans.png)
[英]How to perform logical operation and logical indexing using VIPS in Python?
[英]How to store and read my logical operation on python
我正在制作一個程序來使用一些參數和邏輯運算過濾我的數據。
我有很多教室數據都有它的特點,所以每個教室都會有不同的過濾器。
if classrooms == 1:
if data[A] > data[B] & data[C] != data [D]:
print("matched")
elif classrooms == 2:
if data[A] < data[B] & data[C] == data [D]:
print("matched")
elif classrooms == 3:
if data[B] < data[D] & data[A] == data [C]:
print("matched")
...
...
elif classrooms == 5000:
if data[R] < data[A] & data[W] == data [H]:
print("matched")
由於運算符類似,是否有任何方法可以將我的邏輯過濾器從我存儲的文件中讀取到 python 程序?
"(A<B)&(C!=D)"
"(A>B)&(C==D)"
..
..
"(R<A)&(W==H)"
所以,我不必在 python 中為每個教室編寫所有邏輯過濾器,這會導致 python 中的一行。 我只是從我存儲的文本數據中讀取,我的 python 程序將解釋
"(A<B)&(C!=D)"
到這個程序
if data[A] > data[B] & data[C] != data [D]:
您可以使用正則表達式解析文件中的過濾器,然后從 operator 模塊構造函數鏈來執行過濾器。
這個表情
import re
rx = re.compile(r"""^ # Beginning of string
\( # Opening outer parenthesis
(?P<operand0>[A-Z]) # First operand
(?P<operator0>[^A-Z]+) # First operator
(?P<operand1>[A-Z]) # Second operand
\) # Closing outer parenthesis
(?P<operator1>[^A-Z]+) # Second operator
\( # Opening oute parenthesis
(?P<operand2>[A-Z]) # Third operand
(?P<operator2>[^A-Z]+) # Third operator
(?P<operand3>[A-Z]) # Fourth operand
\) # Closing outer parenthesis
$ # End of string
""",
re.VERBOSE)
匹配您的過濾器的結構。
它們可以這樣匹配:
m = rx.match("(A<B)&(C!=D)")
可以使用(?P<name>)
子表達式中分配的名稱訪問過濾器的某些部分
m['operand0']
'A'
m['operator0']
'<'
使用字典將運算符映射到運算符模塊中的函數
import operator
lookup = {
'<': operator.lt,
'&': operator.and_,
'!=': operator.ne,
}
您可以構建一個表達式並對其進行評估
op0 = lookup[m['operator0']]
op1 = lookup[m['operator1']]
op2 = lookup[m['operator2']]
result = op1(op0(a, b), op2(c, d))
如何從操作數中導出a, b, c, d
是您需要解決的問題。
上面的正則表達式假定操作數是單個大寫字符,運算符是一個或多個非大寫字符。 這可以更精確,例如您可以使用正則表達式交替運算符|
制作一個僅匹配使用的運算符的表達式
r'&|<|>|!=|=='
而不是過於籠統
r'[^A-Z]+'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.