题目描述:
对下面一段文本:
太和殿/ng 俗称/v 金銮殿/n ,/wd 为/v 汉族/nz 宫殿/n 建筑/n 之/uzhi 精华/n ,/wd 东方/s 三/m 大殿/n 之一/rz 。/wj 中国/ns 现存/v 最/d 大/a 的/ude1 木结构/n 大殿/n 。/wj 位于/v 北京/ns 紫禁城/n (/wkz 故宫/ns )/wky 南/f
提取其中的词和对应的词性存到可变数组(vector)中。
解题思路:
首先词和斜杠后面的词性两个字符串都要同时读出,且同时放在向量里,必然要用到结构体,所有把词和词性定义为一个结构体。对结构体进行操作,从文件中读的时候要整体读出,然后再对字符串进行操作,将其分为词和词性存在向量中。
// 提取词和词性.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
struct str{
string word;//词
string tag;//词性
};
int main() {
string a;
str temp;
vector<str> vec;
vector<str>::iterator it;
fstream file;
file.open("test.txt", ios::in);
if (!file) {
cout << "file open error!" << endl;
abort();
}
while (!file.eof()) {
file >> a;
int j = 0;
temp.word = "";
temp.tag = "";
for (int i = 0; i < a.size(); i++) {
j++;
if (a[i] == '/') {
break;
}
}
int length = a.size() - j;
temp.word=a.substr(0, j-1);//截取斜杠前的字符串为词
temp.tag = a.substr(j , length);//截取斜杠后的字符串为词性
vec.push_back(temp);
}
file.close();
for (it = vec.begin(); it != vec.end(); it++)
cout << it->word;
cout<<endl;
system("pause");
}
运行结果: