使用 python 将包含多个值的 FIX 标签写入字典

Writhing FIX tag containing multiple values into a dictionary using python

我正在尝试将 FIX 消息从 .log 文件导出到 .csv 文件。我逐行读取 .log 文件,将标签和值写入字典,然后将字典写入 .csv 文件。我遇到的问题与 FIX 标签 <128> 相关,其中包含多个我无法读取并附加到字典的值。

这是我的代码:

import os
import time
import csv

csvPath = 'C:/""/""/""/""/FixTakerLogs/'

    print('[START]:', 'MsgMarketDataRequest.csv')
    fileLogon = open('C:/""/""/""/""/""/MsgMarketDataRequest.log','r')
    with open(csvPath + 'MsgMarketDataRequest.csv', 'w', newline='') as csvLogon:
        dictLogon = {'8': '','9': '','35': '','49': '','56': '','34': '','52': '','128': '','262': '','263': '','264': '','265': '','267': '','269': '','146': '','55': '','167': '','63': '','12008': '','64': '','193': '','271': '','1201': '','1202': '','1300': '','10': ''}
        csvWriter = csv.DictWriter(csvLogon, dictLogon.keys())
        csvWriter.writeheader()
        for line in fileLogon:
            line = line.rstrip()
            line = line.split(',')
            X = len(line) - 1
            line = line[0:X]
            for tag in line:
                if tag in line:
                    tag = tag.split('=')
                    dictLogon[tag[0]] = tag[1]
            csvWriter.writerow(dictLogon)
    csvLogon.close()
    print('[END]:', 'MsgMarketDataRequest.csv')

这是我正在阅读的行:

'8=FIX.X.X,9=192,35=V,34=XXXX,49=XXX.XXXX.1,56=XXXX.XXXX,52=XXXXXXXX-XX:XX:XX.XX,128=**AAAA**,**BBBB**,262=XXX/XXX-XXXXXXXXXX,263=X,265=X,1021=X,264=X,267=X,269=X,269=X,146=X,55=XXX/XXX,167=XXXXX,1300=X,63=X,10=X'

这是我的引用:

Traceback (most recent call last):
  File "C:/git/Py/exportFixMessagesToExcel.py", line 145, in <module>
    dictLogon[tag[0]] = tag[1]
IndexError: list index out of range

我知道在进入第二个 for 循环之前,我需要找到标记 <128> 拆分它并将两个值写入字典,处理这个问题的最佳方法是什么?谢谢你。

您的以下代码部分一次只读取一行中的一个字母。

for tag in line:
                if tag in line:
                    tag = tag.split('=')
                    dictLogon[tag[0]] = tag[1]

例如,当它执行您描述的 'line' 时,它会保存 tag='8'。所以,它不能分成两部分,因为没有“=”符号。因此 tag[1] 超出范围。

可能的解决方案

#arbitrary value of dictionary and then the line
dictLogon={'firstValue':'34'}
line='8sdf=FIX.X.X,9=192,35=V,34=XXXX,49=XXX.XXXX.1,56=XXXX.XXXX,52=XXXXXXXX-XX:XX:XX.XX,128=**AAAA**,**BBBB**,262=XXX/XXX-XXXXXXXXXX,263=X,265=X,1021=X,264=X,267=X,269=X,269=X,146=X,55=XXX/XXX,167=XXXXX,1300=X,63=X,10=X'

#splitting line for converting it in required list shape
line = line.split(',')

#removing the values without '=' sign
line=[ x for x in line if "=" in x ]
for i in range(len(line)):
    a = line[i].split('=')
    dictLogon[a[0]] = a[1]

我建议您将原始文件 .log 更改为使用“;”作为分隔符而不是“,”,或将“AAAA,BBBB”中的“,”更改为其他字符,如 space。

如果你不想那样做,方法如下:

tag = tag.split('=')
if len(tag) > 1: #This means = exists
    key = tag[0]  # Store the key for later use
    ictLogon[key] = tag[1]
else:  # There is no =, so it should be part of the values for the former key
    dictLogon[key] += ' ' + tag[0] # Use space instead of ',' since ',' is used as the separator in dictionary