Как посчитать слова в Word

Люди помогите мне ламеру. Как посчитать количество слов в файле *.doc

высылай файл и слово, посчитаю

нечего высылать. Задача такая. Есть вордовский файл. В программе надо указать путь к этому файлу. А в качестве результата , программа должна выводить. напремер в label!.caption количество слов

ладно, тебе повезло что я сегодня возлиятельно-добрый… function WordCount(p_strFileName,p_strWord:string):integer; var f:file; buf:string; _MyPos:integer; begin Result:=0; AssignFile(f,p_strFileName);reset(f,1); SetLength(Buf,FileSize(f)); BlockRead(f,Buf[1],FileSize(f)); Repeat _MyPos:=Pos(p_strWord,Buf); if _MyPos<>0 then begin Buf:=Copy(Buf,_MyPos+Length(p_strWord),Length(Buf)); Result:=Result+1; end; Until _MyPos=0; CloseFile(f); end; procedure TForm1.Button1Click(Sender: TObject); begin if OpenDialog1.Execute then Label1.Caption:="Количество слов ""+Edit1.Text+" в файле Word ""+OpenDialog.FileName+"" равно:"+IntToStr(WordCount(OpenDialog1.FileName,Edit1.text)); end;

огромное спаибо, но у меня он чего то ругаеться блин, [Error] Unit1.pas(49): Undeclared identifier: «OpenDialog1» [Error] Unit1.pas(49): «THEN» expected but identifier «Execute» found [Error] Unit1.pas(50): Illegal character in input file: """ ($22) [Error] Unit1.pas(50): Illegal character in input file: """ ($22) [Error] Unit1.pas(50): Illegal character in input file: "«" ($22) [Error] Unit1.pas(61): Statement expected but end of file found [Fatal Error] Project1.dpr(5): Could not compile used unit «Unit1.pas»

ну такого я не ожидал…. занеси на форму: из вкладки Dialogs, компонент TOpenDialog из вкладки Standary, TEdit и TLabel

OpenDialog1 — это диалог (с закладки Dialogs), который там называется OpenDialog. Когда первый кидаешь на форму, его назовет OpenDialog1. Пользуйся 🙂

гы:)) торможу. прога теперь запускаеться, но результат все время один и тот же. 0 . хоть ты открываешь файл с 10 страницами текста, или с пару словами :((

> Palladin © (25.05.03 21:26) > ладно, тебе повезло что я сегодня возлиятельно-добрый… Э-э-э, а вы Word-ый документ в блокнотике открывали когда-нибудь? > kamkad3e (25.05.03 20:35) > Люди помогите мне ламеру. Как посчитать количество слов > в файле *.doc Примерный алгоритм действий такой, создать Ole-объект типа Word.Application, открыть им файл, взять текст, обработать. Подробней не пишу, т.к. специально этим не занимался. Кое что можно взять например здесь http://www.delphimaster.ru/cgi-bin/faq.pl?look=1&id=988619885&n=18 А так в поиск, и менее общие вопросы в конференцию

> NailS © (25.05.03 22:05) Э-э-э, а вы в FAR его открывали когда нибудь? Однако блокнотик совсем не показатель! > kamkad3e (25.05.03 22:04) Ты, блин, надеюсь case-sensitivity соблюдаешь? Ты же понимаешь «попа» и «Попа» различаются…

Небольшое уточнение к ответу Palladin Word хранит текст к Unicode, соответственно читать надо в WideString function WordCount(p_strFileName,p_strWord:string):integer; var f:file; buf:WideString; _MyPos:integer; begin Result:=0; AssignFile(f,p_strFileName);reset(f,1); SetLength(Buf,FileSize(f) div 2); BlockRead(f,Buf[1],FileSize(f)); Repeat _MyPos:=Pos(p_strWord,Buf); if _MyPos<>0 then begin Buf:=Copy(Buf,_MyPos+Length(p_strWord),Length(Buf)); Result:=Result+1; end; Until _MyPos=0; CloseFile(f); end;

> jack128 © (25.05.03 23:13) во истину, ты прав, хоть и невсегда он их так хранит… например в 6,5 ворде както без этого… лучше проанализировать, хотя черт его знает как его проанализировать… может локал сеттингс посмотреть на предмет кириллицы… тогда и сохраненки будут другие… но если сохранен на другом компе с другими локал сеттингсами… кароче, думайте сами, решайте сами, чего же вам иметь, лучьше всего считать после позиции 512 4 символа и проверить первый и третий на значение 4, если вдург меньше четырех то точно unicode и точно следует читать как jack128, а если вдруг не 4 то проверить на попадание первого и третьего в интервал допустимых символов латинцы и криллицы, если вдруг оба попадают, то очень большая вероятность что читать надо как мой первый вариант… хау, я все сказал…

> NailS © (25.05.03 22:05) ты бы еще jpg в блокноте открыл…

мне надо не количество уникальных слов, а количество всех слов. Мне кажеться что можно как то через OLE добраться до свойствадокумента. Ведь ворд жранит количество знаков, сторк, количество слов.

Может здесь найдешь что-нибудь интересное http://www.delphikingdom.ru/helloworld/msword.htm

спасибо, а может кто чего еще посоветует

где можно почитать про WordApplication1.Documents.Open(). У меня delphi 5 ,я начал искать в word97.pas но что-то совсем запутался. а вообще спасибо огромное 2 NailS, я от туда много полезного узнал

Все элементарное просто: посмотри в MS VBA Help для Word. Там все описано как и чего.

Во-во, послушай Endi. Кстати, там же можно найти, как называются нужные тебе свойства. (по моему document.properties. …)

гы, спасибо, вот выкопал в msdn , может кому еще понадобиться expression.Open(FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenConflictDocument, OpenAndRepair , DocumentDirection, NoEncodingDialog) expression Required. An expression that returns a Documents object. FileName Required Variant. The name of the document (paths are accepted). ConfirmConversions Optional Variant. True to display the Convert File dialog box if the file isn"t in Microsoft Word format. ReadOnly Optional Variant. True to open the document as read-only. Note This argument doesn«t override the read-only recommended setting on a saved document. For example, if a document has been saved with read-only recommended turned on, setting the ReadOnly argument to False will not cause the file to be opened as read/write. AddToRecentFiles Optional Variant. True to add the file name to the list of recently used files at the bottom of the File menu. PasswordDocument Optional Variant. The password for opening the document. PasswordTemplate Optional Variant. The password for opening the template. Revert Optional Variant. Controls what happens if FileName is the name of an open document. True to discard any unsaved changes to the open document and reopen the file. False to activate the open document. WritePasswordDocument Optional Variant. The password for saving changes to the document. WritePasswordTemplate Optional Variant. The password for saving changes to the template. Format Optional Variant. The file converter to be used to open the document. Can be one of the following WdOpenFormat constants. WdOpenFormat can be one of these WdOpenFormat constants. wdOpenFormatAllWord wdOpenFormatAuto The default value. wdOpenFormatDocument wdOpenFormatEncodedText wdOpenFormatRTF wdOpenFormatTemplate wdOpenFormatText wdOpenFormatUnicodeText wdOpenFormatWebPages To specify an external file format, apply the OpenFormat property to a FileConverter object to determine the value to use with this argument. Encoding Optional Variant. The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. For the list of valid MsoEncoding constants, see the Object Browser in the Visual Basic Editor. The default value is the system code page. Visible Optional Variant. True if the document is opened in a visible window. The default value is True. OpenConflictDocument Optional Variant. Specifies whether to open the conflict file for a document with an offline conflict. OpenAndRepair Optional Variant. True to repair the document to prevent document corruption. DocumentDirection Optional WdDocumentDirection. Indicates the horizontal flow of text in a document. WdDocumentDirection can be one of these WdDocumentDirection constants. wdLeftToRight default wdRightToLeft NoEncodingDialog Optional Variant. True to skip displaying the Encoding dialog box that Word displays if the text encoding cannot be recognized. The default value is False.

Если интересует могу кинуть на мыло DOC «MSWord вместо QReport» Там так же есть и про статистику документов…

Наверх

Поделиться:
Нет комментариев

Добавить комментарий

Ваш e-mail не будет опубликован. Все поля обязательны для заполнения.

×
Рекомендуем посмотреть