Создать словарь слов встречающихся в текстовом файле - C#
Формулировка задачи:
Очень нужно. Получил задание - осуществить обработку текстового файла, содержащего некоторый многостраничный текст. Результат обработки – текстовый файл, содержащий предметный указатель встречающихся в тексте слов. Вот нашел в старых своих работах что-то подобное, но на С++. Пока сложно с файлами и строками на С#, может кто поможет перевести имеющийся код на С#?
Очень надо. Пытался сам перевести, но какая-то ерунда получается. Спасибо!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define SEPLINE "----------------------------------------\n"
typedef struct {
char *wrd;
size_t cnt;
} Wrd_t;
int wrdcmp(const void *a, const void *b){
return strcmp((*(Wrd_t*)a).wrd, (*(Wrd_t*)b).wrd);
}
int cntcmp(const void *a, const void *b){
return (*(Wrd_t*)b).cnt - (*(Wrd_t*)a).cnt;
}
int main(void){
char buf[BUFSIZ], *p;
Wrd_t *words;
size_t count, i;
FILE *f;
int action;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
printf("Имя файла: ");
if ( !fgets(buf, sizeof(buf), stdin) )
exit(1);
if ( p = strrchr(buf, '\n') )
*p = '\0';
if ( !*buf )
exit(1);
if ( ( f = fopen(buf, "r") ) == NULL ){
perror("Не могу открыть файл!\n");
exit(1);
}
words = NULL;
count = 0;
while ( fscanf(f, "%s", buf) == 1 ){
for ( i = 0; i < count; ++i ){
if ( !strcmp(words[i].wrd, buf) ){
++(words[i].cnt);
break;
}
}
if ( i == count ){
if ( ( words = (Wrd_t*)realloc(words, sizeof(Wrd_t) * (count + 1)) ) == NULL ){
perror("Ошибка памяти!\n");
exit(1);
}
if ( ( words[i].wrd = strdup(buf) ) == NULL ){
perror("Ошибка памяти!\n");
exit(1);
}
words[i].cnt = 1;
++count;
}
}
if ( ferror(f) ){
perror("Ошибка чтения из файла!\n");
exit(1);
}
fclose(f);
if ( !words || !count ){
perror("Ошибка чтения из файла!\n");
exit(1);
}
printf("\nНайдено %d слов.\nСортировать по\n1 - алфавиту\n2 - количеству\n> ", count);
scanf("%d", &action);
switch ( action ){
case 1 :
qsort(words, count, sizeof(Wrd_t), wrdcmp);
break;
case 2 :
qsort(words, count, sizeof(Wrd_t), cntcmp);
break;
}
printf("\n%sСлово Встретилось (раз)\n%s", SEPLINE, SEPLINE);
for ( i = 0; i < count; ++i )
printf("%-20s%d\n", words[i].wrd, words[i].cnt);
printf("%s\n", SEPLINE);
for ( i = 0; i < count; ++i ){
if ( words[i].wrd != NULL){
free(words[i].wrd);
words[i].wrd = NULL;
}
}
free(words);
words = NULL;
exit(0);
}Решение задачи: «Создать словарь слов встречающихся в текстовом файле»
textual
Листинг программы
private string ReadFile(string location)
{
try
{
using (StreamReader sr = new StreamReader(location))
{
return sr.ReadToEnd();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return null;
}
private List<string> GetWords(string str)
{
char[] separator = new char[7];
string[] result;
separator[0] = ';';
separator[1] = ' ';
separator[2] = '.';
separator[3] = ',';
separator[4] = ':';
separator[5] = '(';
separator[6] = ')';
result = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return new List<string>(result.ToList().Distinct().OrderBy(q => q));
}
//Вызов:
string str = ReadFile("M://test.txt");
var list = GetWords(str);
foreach (var word in list )
{
MessageBox.Show(word);
}