情感分析系统的预处理工作

老板给了个情感分析系统的任务,一开始各种纠结不知道怎么入手。再三拖延后看了篇论文,知道了有个SVMLight的现成系统可以用,但是要把文件处理成它规定的格式,于是就是这篇文章的主要内容了。

主要工作就是将一个文件夹下的源文件转换成单个词存在另一个文件夹下边。最终目标当然是转换成SVMLight要求的格式。这块后边看看特征采集再实现。

整个结构就是将文件夹下边的文件依次读出,经过wordProcess后再经历stopwordList剔除。统计数目存入目标文件夹。都是些stl,网上搜的,没啥技术含量,鼓捣了半天竟然有些成就感,真是太扯淡了。

遇到的新知识有:

1.读取文件夹下的所有文件然后处理。用到了afx.h这个头文件下的CFileFind。记住需要设置project-》settings-》general-》use MFC as a  shared DLL。文件名操作各种无力吐槽。

2.fstream多次读取文件时,调用完close还要调用个clear。。。没用上,几下备用吧

ifstream类使用心得一则


为了方便stopwordlist和final处理,停止词和处理文本用map存储。


#include<iostream>
#include<fstream>
#include<string>
#include<map>
#include<cctype>
#include<afx.h>
using namespace std;

map<string,int> stoplist;
map<string,int> punc;
map<string,int> final;
string filenames[60000];

void FindAllFile(string path,string * filenames,int & count)
{
 CFileFind finder;
 bool working = finder.FindFile((path+"\\*.*").c_str());
 while (working)
 {
  working = finder.FindNextFile();
  if (finder.IsDots())
   continue;
  if (finder.IsDirectory())
  {
   //FindAllFile(finder.GetFilePath(), filenames, count);
  }
  else
  {
   string filename = finder.GetFileName();
   filenames[count++] = filename;
  }
 }
}


//wordProcess将首字母小写+去掉末尾标点
void wordProcess(string &str)
{
 if(!str.empty())
 {
  if(isalpha(str[0])&&isupper(str[0]))
    str[0]=tolower(str[0]);
  if(isalpha(str[0])&&!isalpha(str[str.size()-1]))
   str.erase(str.end()-1);
  if(!isalpha(str[0]))   //遇到中文字符会出错
   str.erase(str.begin());
 }
}

void process()
{
    /*初始化stop词典后续添加positive和negative词典*/
 string temp;
 int count=0;
 ifstream fin("../stopwordlist.txt",ios::in);
 while(fin>>temp)
  stoplist.insert(pair<string,int>(temp,++count));
 fin.close();
//连续打开文件
        fin.clear(ios::goodbit);
   
//*********************************************************************循环读取文件夹下的文件 
 int i;
 int fileNum=0;
 FindAllFile("../source",filenames,fileNum);

/***********************处理每一个文件*************************/
 for(i=0;i<fileNum;++i)
 {
//source 后边的\\必须加上,理解为文件夹下了下边destination一样
        ifstream fin(("../source\\"+(string)filenames[i]).c_str());
  ofstream fout(("../destination\\"+(string)filenames[i]).c_str());
  string str;
  final.erase(final.begin(),final.end());
  while(fin>>str)
  {
   wordProcess(str);
   if(isdigit(str[0]))
    continue;
   if(stoplist.find(str)==stoplist.end())
   {
    if(final.find(str)==stoplist.end())
     final.insert(pair<string,int>(str,1));
    else
     final[str]++;
   }
  }

  //将处理过的文件输出,这里可以添加向量转换
  for(map<string,int>::iterator iter=final.begin();iter!=final.end();++iter)
   fout<<(*iter).first<<" "<<(*iter).second<<endl;
 }
}

int main(int argc,char * argv[])
{
 process();
   
 return 0;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值