从文本文件读取一组词组,并保存在向量中

题目描述:
对下面一段文本:
太和殿/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");
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值