【问题标题】:Filtering elements from a string input从字符串输入中过滤元素
【发布时间】:2020-03-07 03:15:56
【问题描述】:

给出以下字符串:

mystring = "animals.dog > 12 and type.type_id=105 and colors.name='yellow'"

我想从此字符串返回以下元素。

table1 = animals
element1 = dog 
operator1= greater

table2 = type 
element2 = type_id
operator2= equal

table3 = colors
element3 = name
operator3 = equal

我只对前3部分感兴趣,即table.element操作符(例如animals.dog>)

不幸的是,我已经将句子转换为列表失败了

我目前尝试了以下方法,但是使用这种方法,运算符不会被阅读。

import re 
mystring = "animals.dog > 12 and type.type_id=105 and colors.name='yellow'"
wordList = re.sub("[^\w]", " ",  mystring).split()

如果你能帮助我,我会很高兴的。 最好的问候

【问题讨论】:

  • 写一个小解析器。
  • 如果是python代码,请使用ast.parse

标签: python string list return


【解决方案1】:

这是适用于本示例的正则表达式:

out = re.findall("([^\W]+)\.([^\W]+)\W*([<>=])", mystring)

输出:

[('animals', 'dog', '>'), ('type', 'type_id', '='), ('colors', 'name', '=')]

但它不支持&gt;=&lt;= 等运算符。如果您需要它们,则需要在正则表达式中指定它们。

有了输出列表,你可以像这样迭代它:

for table, element, operator in out:
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多