读取样本下的基本行为文件并将其处理成LibSVM需要的格式

SVM是一种很强大的的机器学习分类算法,在很多诸如文本分类,图像分类,生物序列分析和生物数据挖掘,手写字符识别等领域有很多的应用。具体理论性的东西参考博文http://www.dataguru.cn/forum.php?mod=viewthread&tid=371987 看完还是似懂非懂。

最近在做SVM分类,处理对象是恶意程序动态分析生成的基本行为文件,它是1*811的0、1串,libsvm需要的格式是label index:value,刚开始想采用python实现,由于其文件操作没有很强大,勿喷可能是我对python不熟。最后用C++实现了,期间也出现了一些问题,最后搞定了。

下面把代码贴出来:

首先是用python实现的从样本分析结果中找出基本行为文件,由于基本行为文件都是带有result_txt后缀的,代码如下:

#! /usr/bin/python
import os
import shutil

#抽取样本运行结果中的基本业务特征
dpath = r"C:UsersxdDesktop1.12360	est0"
rpath = r"C:UsersxdDesktop1.12360	est"

filenames = os.listdir(dpath)
for filename in filenames:
    filepath=dpath+"/"+filename
    if os.path.isdir(dpath):
        names=os.listdir(filepath)
        for name in names:
            if (name == filename + "_"+"result.txt"):
                fpath = filepath + "/" + name
                shutil.copy(fpath,rpath)

C++实现对文件夹下的基本行为文件进行文件格式转换的代码:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <io.h>
#include <vector>
#include <string>
using namespace std;

void getFiles( string path, vector<string>& files );
void main()
{
    int a[812];    
    ifstream f;
    a[0]=1;
    char s;
    //char *ss;
    char * filepath="C:\Users\xd\Desktop\1.12\360\test";
    vector<string> files;
    getFiles(filepath,files);
    int size = files.size();  
    
    ofstream f1;
    f1.open("e:\test.txt");

    for (int i = 0;i < size;i++)  
    {  
        cout<<files[i].c_str()<<endl; 
        //ss=files[i].c_str();
        f.open(files[i].c_str());
        for (int n=1;n<=811;n++)
        {
            s=f.get();
            a[n]=s-'0';
        }
        f.close();
        
        f1<<a[0]<<" ";
        for(int j=1;j<=811;j++)
        {
            f1<<j<<":"<<a[j]<<" ";
        }
        f1<<endl;
        
    }
    f1.close();
}
void getFiles( string path, vector<string>& files )
{
    long   hFile   =   0;
    struct _finddata_t fileinfo;
    string p;
    if((hFile = _findfirst(p.assign(path).append("\*").c_str(),&fileinfo)) !=  -1)
    {
        do
        {
            if((fileinfo.attrib &  _A_SUBDIR))
            {
                if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)
                    getFiles( p.assign(path).append("\").append(fileinfo.name), files );
            }
            else
            {
                files.push_back(p.assign(path).append("\").append(fileinfo.name) );
            }
        }while(_findnext(hFile, &fileinfo)  == 0);
        _findclose(hFile);
    }
}
原文地址:https://www.cnblogs.com/xiaodi914/p/5492455.html