如何使用python从代码中提取数据

时间:2018-09-27 13:22:19

标签: python text-extraction

我有一些功能,如.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
  • 今天的条目(日期)<1
  • 结束调查
  • EntCondL

并使用python识别=<符号。 预先感谢。

2 个答案:

答案 0 :(得分: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']

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

答案 1 :(得分:1)

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