def parse_wolfram(file_pointer):
# the first line is the header, which we ignore
_ = file_pointer.readline()
row_str = str()
out_data = []
while True:
# Read each line till EOF stripping leading and trailing white spaces
line = file_pointer.readline().strip()
if not line:
break
# Append each line as a string to the current row
row_str += line
# Find '}' to detect the end of a row
if line.find('}') > 0:
# Parse the row:
# 1. Use the regular expression module to split the string
# where the delimiter is one or more of the character set.
# This produces a list of string tokens.
# 2. [1:-1] removes the empty string tokens at the head and
# tail of this list
# 3. Use list comprehension to cast string tokens to float.
# 4. Append list of floats for each row to output list of lists (2-D array)
out_data.append([float(data) for data in re.split(r'[{, }]+', row_str)[1:-1]])
# Reset for next row
row_str = str()
return out_data
Hard to say if the following is elegant or pretty, but I believe that it is somewhat 'pythonic'. We can parse the Wolfram output as specified using the following function that takes as input an opened file pointer to the file:
def parse_wolfram(file_pointer):
# the first line is the header, which we ignore
_ = file_pointer.readline()
row_str = str()
out_data = []
while True:
# Read each line till EOF stripping leading and trailing white spaces
line = file_pointer.readline().strip()
if not line:
break
# Append each line as a string to the current row
row_str += line
# Find '}' to detect the end of a row
if line.find('}') > 0:
# Parse the row:
# 1. Use the regular expression module to split the string
# where the delimiter is one or more of the character set.
# This produces a list of string tokens.
# 2. [1:-1] removes the empty string tokens at the head and
# tail of this list
# 3. Use list comprehension to cast string tokens to float.
# 4. Append list of floats for each row to output list of lists (2-D array)
out_data.append([float(data) for data in re.split(r'[{, }]+', row_str)[1:-1]])
# Reset for next row
row_str = str()
return out_data
This function can be used as such on the file named 'chain.m' if that file is formatted as the OP suggests:
发布评论
评论(1)
很难说以下内容是优雅的还是漂亮的,但我认为这有点“ Pythonic”。我们可以使用以下函数来解析Wolfram输出,该函数将其作为输入输入到该文件的打开文件指针:
如果该文件格式化为OP建议:该函数可以在名为'chain..m'的文件上使用。
该输出是浮子列表的python列表。可以使用
numpy.Array(parsed_output)
将其转换为numpy
数组。Hard to say if the following is elegant or pretty, but I believe that it is somewhat 'pythonic'. We can parse the Wolfram output as specified using the following function that takes as input an opened file pointer to the file:
This function can be used as such on the file named 'chain.m' if that file is formatted as the OP suggests:
This output is a python list of lists of floats. This can be converted to a
numpy
array usingnumpy.array(parsed_output)
.