Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 09.05.2011, 17:03   #1
lineico
 
Регистрация: 09.05.2011
Сообщений: 5
Восклицание В заданном текстовом файле подсчитать частоту использования каждого слова из словаря (другого текстового

В заданном текстовом файле подсчитать частоту использования
каждого слова из словаря (другого текстового файла).

Нужно решить на С помогите плз !!
lineico вне форума Ответить с цитированием
Старый 09.05.2011, 17:57   #2
Сtrl
C++
Форумчанин
 
Аватар для Сtrl
 
Регистрация: 27.03.2011
Сообщений: 803
По умолчанию

Сделал на C++, на C сам переделаешь.
Код:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

#define IS_LIT_LAT_SYM(C) (((C) >= 'a') && ((C) <= 'z'))
#define IS_BIG_LAT_SYM(C) (((C) >= 'A') && ((C) <= 'Z'))
#define IS_LAT_SYM(C) ((IS_LIT_LAT_SYM(C)) || (IS_BIG_LAT_SYM(C)))


class WordList
{
public:
	struct Word
	{
		string text;
		unsigned int repeats;
		Word(Word& copy_from) : text(copy_from.text), repeats(copy_from.repeats) {}
		Word(const string text, const unsigned int repeats) : text(text), repeats(repeats) {}
	};
	typedef vector<Word> words_t;
protected:
	words_t words;
public:
	WordList(void){words.clear();}
	WordList(const WordList& copy_from){this->words = copy_from.words;}
	~WordList(void){}
public:
	void Clear(void) {words.clear();}
	void ReadDictionaryFromString(string str)
	{
		string::iterator pcur = str.begin();
		string::iterator plast = str.end();
		while (pcur != plast)
		{
			string wordtext = "";
			while ((pcur != plast) && (!IS_LAT_SYM(*pcur)))
				++pcur;
			while ((pcur != plast) && (IS_LAT_SYM(*pcur)))
				wordtext += *(pcur++);
			if (!wordtext.empty())
				words.push_back(Word(wordtext, 0));
		}
	}

	void ReadDictionaryFromFile(const string filename)
	{
		ifstream file;
		file.open(filename);
		if (!file)
			return;
		while (!file.eof())
		{
			string buffer;
			getline(file, buffer);
			this->ReadDictionaryFromString(buffer);
		}
		file.close();
		return;
	}

	void AddRepeat(string str)
	{
		words_t::iterator pcur = words.begin();
		words_t::iterator plast = words.end();
		while (pcur != plast)
		{
			if (pcur->text == str)
				++(pcur->repeats);
			++pcur;
		}
	}
	
	void CalcRepeatsInString(string str)
	{
		string::iterator pcur = str.begin();
		string::iterator plast = str.end();
		while (pcur != plast)
		{
			string wordtext = "";
			while ((pcur != plast) && (!IS_LAT_SYM(*pcur)))
				++pcur;
			while ((pcur != plast) && (IS_LAT_SYM(*pcur)))
				wordtext += *(pcur++);
			if (!wordtext.empty())
				AddRepeat(wordtext);
		}
		return;
	}

	void CalcRepeatsInFile(const string filename)
	{
		ifstream file;
		file.open(filename);
		if (!file)
			return;
		while (!file.eof())
		{
			string buffer;
			getline(file, buffer);
			this->CalcRepeatsInString(buffer);
		}
		file.close();
		return;
	}

	void Print(void)
	{
		words_t::iterator pcur = words.begin();
		words_t::iterator plast = words.end();
		while (pcur != plast)
		{
			cout << pcur->text << ":\t" << pcur->repeats << endl;
			++pcur;
		}
	}
};

int main(void)
{
	WordList wordlist1;
	wordlist1.ReadDictionaryFromFile("dict.txt");
	wordlist1.CalcRepeatsInFile("text.txt");
	wordlist1.Print();
	cin.get();
	return 0;
}
Ищете информацию по C++?
cplusplus.com
Сtrl вне форума Ответить с цитированием
Старый 09.05.2011, 18:02   #3
Сtrl
C++
Форумчанин
 
Аватар для Сtrl
 
Регистрация: 27.03.2011
Сообщений: 803
По умолчанию

Если нужно, чтобы Print все ровно выводил, переделываешь его так:
Код:
	void Print(void)
	{
		words_t::iterator pcur = words.begin();
		words_t::iterator plast = words.end();
		int maxwordtextlength = 0;
		while (pcur != plast)
		{
			if (pcur->text.length() > maxwordtextlength)
				maxwordtextlength = pcur->text.length();
			++pcur;
		}
		
		pcur = words.begin();
		while (pcur != plast)
		{
			cout << pcur->text << ':';
			for (int i = pcur->text.length(); i < maxwordtextlength; ++i)
				cout << ' ';
			cout << '\t' << pcur->repeats << endl;
			++pcur;
		}
	}
Ищете информацию по C++?
cplusplus.com
Сtrl вне форума Ответить с цитированием
Старый 09.05.2011, 19:09   #4
Rififi
Старожил
 
Регистрация: 19.08.2009
Сообщений: 2,119
По умолчанию

на Си делать лень, ибо гемора много, на C++ гораздо легче...

Код:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <string>
#include <map>
#include <locale>

typedef std::map<std::string, size_t> Dict;
typedef std::istream_iterator<std::string> I;

void reset_dict(const std::string& fileName, Dict& d)
{
	d.clear();

	std::ifstream ifs(fileName);
	for (I it(ifs); it != I(); ++it)
		d.insert(Dict::value_type(*it, 0));
}

void fill_dict(const std::string& fileName, Dict& d)
{
	std::ifstream ifs(fileName);
	for (I it(ifs); it != I(); ++it)
	{
		const Dict::iterator found = d.find(*it);
		if (found != d.end())
			found->second++;
	}
}

int main()
{
	setlocale(LC_ALL, "");

	Dict d;
	
	reset_dict("dict.txt", d);
	fill_dict("text.txt", d);

	for (Dict::const_iterator it = d.begin(); it != d.end(); ++it)
		std::cout << it->first << " : " << it->second << std::endl;

	return 0;
}
Rififi вне форума Ответить с цитированием
Старый 09.05.2011, 19:35   #5
Сtrl
C++
Форумчанин
 
Аватар для Сtrl
 
Регистрация: 27.03.2011
Сообщений: 803
По умолчанию

Rififi, да уж, в STL я не силен, так что ваше решение куда лучше получилось :)
Ищете информацию по C++?
cplusplus.com
Сtrl вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Подсчитать количество вхождений в слова первого слова. 07412 Общие вопросы C/C++ 4 27.05.2010 12:05
Разбить текст на слова и произвести поиск каждого слова по текстовому массиву Burning_brook Microsoft Office Excel 2 22.05.2010 01:56
Поиск данных в текстовом файле (в самом файле! а не в Memo и не загружая всю инфу из файла в одну строку glagoff Помощь студентам 1 05.05.2010 13:00
Отсортировать слова в заданном списке по алфавиту. Nynka Помощь студентам 5 08.12.2009 00:45
Найти (в процентах) частоту появления каждого из m наиболее часто встречающихся элементов sk1p Паскаль, Turbo Pascal, PascalABC.NET 2 26.09.2008 23:57