笔者从事的工作经常使用HFSS进行电磁仿真,仿真得到的结果经常需要导入到Matlab中使用,而HFSS输出的数据格式和Matlab格格不入,给我增加了很多工作量,考虑到最近在自学python,很多大牛都在用它来处理文本,我想应该可以通过它方便的处理我的数据。简单的脚本程序代码如下:
#2012.2.22
#Get all HFSS's Export files and change the format to matlab data file
import os
path = os.getcwd() #Get the current work address
files = os.listdir(path) #Get the file list
for f in files:
N=len(f);
if f[N-3]=='t' and f[N-2]=='x' and f[N-1]=='t':
fp = open(f,'r')
words=fp.read()
fp.close()
fp = open(f,'w')
m=len(words)
for i in range(0,m-1):
if words[i+1]=='.' and words[i]<='9' and words[i]>='0':
fp.write(words[i:m])
break
fp.close()
print f
使用起来很简单,在HFSS中,输出数据使用*.txt格式,之后在该文本文件所在目录运行该脚本,原理生成的txt文件中的无用信息就被去掉了,可以被matlab直接读取了。该脚本可以自动处理所在目录下的所有txt文件,方便又快捷!初步了解了python脚本的强大!
以上程序只是寻找了当前目录下的所有txt文件,将HFSS生成的txt数据文件前面的文字描述去掉,但是还是要一点一点敲代码,把数据读取到matlab中,为了省掉最后一点功夫,对以上代码进行修改,运行修改后的脚本后,会在剪片版中自动生成matlab语句,将所有文本文件中的数据载入到matlab在。修改版的代码如下:
#Edit By Jeff Xu jeff890309@gmail.com
#2012.2.22
#Get all HFSS's Export files and change the format to matlab data file
#Vision 1.2
#Creat m file to plot the rusult
import os
import win32clipboard as wincb
import win32con
Code0="p"
Code1="load('"
Code=""
k=0;
wincb.OpenClipboard() #open ClipBoard
wincb.EmptyClipboard() #clear ClipBoard
path = os.getcwd() #Get the current work address
files = os.listdir(path) #Get the file list
for f in files:
N=len(f);
if f[N-3]=='t' and f[N-2]=='x' and f[N-1]=='t':
fp = open(f,'r')
words=fp.read()
fp.close()
fp = open(f,'w')
m=len(words)
for i in range(0,m-1):
if words[i+1]=='.' and words[i]<='9' and words[i]>='0':
fp.write(words[i:m])
break
fp.close()
print f
k=k+1
Code=Code+'p'+str(k)+"=load('"+path+'\\'+f+"');"
wincb.SetClipboardData(win32con.CF_TEXT,Code)
wincb.CloseClipboard()