【问题标题】:how to extract data from a code using python如何使用python从代码中提取数据
【发布时间】:2018-09-27 13:22:18
【问题描述】:

我有一些函数,如使用简单语言编写的 .txt 文件,我需要使用 python 从这些函数中提取数据。例如,考虑以下部分。

代码段 -

If MarketPosition = 0 and (EntriesToday(Date) < 1 or EndofSess) and
EntCondL 
then begin
    Buy("EnStop-L") NShares shares next bar at EntPrL stop;
end;

在这里,我需要提取零件

  • MarketPosition = 0
  • EntriesToday(日期)
  • 结束会议
  • EntCondL

并使用 python 识别=&lt; 标志。 提前致谢。

【问题讨论】:

  • 你可能需要一个语言解析器或lexer
  • 总是在If...then 之间还是只是一个例子?
  • @Venify 它总是介于 If...then 和 end;

标签: python text-extraction


【解决方案1】:

这里是在ifthen 之间查找和拆分文本的示例 结果是各个元素的列表:变量、括号和比较运算符。

code = """
If MarketPosition = 0 and (EntriesToday(Date) < 1 or EndofSess) and
EntCondL 
then begin
    Buy("EnStop-L") NShares shares next bar at EntPrL stop;
end;
"""

import re
words = re.split("\s+|(\(|\)|<|>|=|;)", code)

is_if = False
results = []
current = None
for token in words:
    if not token:
        continue
    elif token.lower() == "if":
        is_if = True
        current = []
    elif token.lower() == "then":
        is_if = False
        results.append(current)
    elif is_if:
        if token.isdecimal(): # Detect numbers
            try:
                current.append(int(token))
            except ValueError:
                current.append(float(token))
        else: # otherwise just take the string
            current.append(token)



print(results)

结果:

['MarketPosition', '=', 0, 'and', '(', 'EntriesToday', '(', 'Date', ')', '<', 1, 'or', 'EndofSess', ')', 'and', 'EntCondL']

我认为从这里出发更容易 (我不知道您需要哪种形式的数据,例如括号是否重要?)

【讨论】:

  • 正如你所说,括号实际上并不重要......我能够通过你的代码片段完成工作。再次感谢
【解决方案2】:

我认为您正在寻找某些运算符的前缀和后缀
我建议您找到这些运算符列表并使用它的位置来获取前缀和后缀

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 2022-01-04
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多