![](/img/trans.png)
[英]Most efficient way to extract PyTables table with stored colnames as variable names
[英]Optimal way to parse an if condition to extract variable names
我有一個 if 條件作為字符串,並且想要提取變量名。
示例 1:
Input: "((a>5 and b<20) or (c>30))"
Output: {"a", "b", "c"}
示例 2:
Input: "a==20"
Output: {"a"}
僅提取變量名的最佳方法是什么?
正則表達式會為此工作嗎? 條件可以是任意長度。
我還考慮過在空間上拆分,然后修剪掉不需要的字符,直到我們只得到變量名。
任何類似 Python 的標識符都符合定義良好的正則表達式:
ident = "[a-zA-Z_][a-zA-Z_0-9]*"
只要您沒有帶引號的字符串,您就可以在表達式中找到所有標識符,然后刪除所有關鍵字(它們的列表已關閉),例如:
keywords = {"and", "or"} # Expand as needed
s = "((a>5 and b<20) or (c>30))"
[i for i in re.findall(ident, s) if i not in keywords]
#['a', 'b', 'c']
請注意,如果存在常量字符串(例如'abc'
),它可能會被錯誤地識別為變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.