Solved

Coding

Posted on 2004-11-01
160 Views
Last Modified: 2012-05-05
I have tried and still trying to write a code that counts words, sentences and paragraphs can some one tell me how?
0
Question by:Marches
    3 Comments
     
    LVL 19

    Expert Comment

    by:arif_eqbal
    Trying to count chars, words from where ???

    If you are using RichTextBox you'll need to check spaces for word count char count you can get by length property and so on.

    However there's a trick What you can do is Open word using Word.Application transfer all the contents to it and then use the built in Word properties to get the Char, Words and Sentences count.

    If you want I can post a sample for you.

    0
     
    LVL 27

    Accepted Solution

    by:
    Sample code.....

    'FORM1

    Imports System.IO
    Imports StringProcessor
    Public Class frmMain
        Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "

        Public Sub New()
            MyBase.New()

            'This call is required by the Windows Form Designer.
            InitializeComponent()

            'Add any initialization after the InitializeComponent() call

            Dim sPath As String
            sPath = "c:\testme.txt"

            Dim o As New StringProcessor.Course.StringProcessor
            o.ProcessFile(sPath)
            txtWords.Text = o.Word
            txtChars.Text = o.Character
            txtSentences.Text = o.Sentence
            txtParagraphs.Text = o.Paragraph
        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents lblChars As System.Windows.Forms.Label
        Friend WithEvents lblWords As System.Windows.Forms.Label
        Friend WithEvents lblSentences As System.Windows.Forms.Label
        Friend WithEvents lblParagraphs As System.Windows.Forms.Label
        Friend WithEvents txtWords As System.Windows.Forms.TextBox
        Friend WithEvents txtSentences As System.Windows.Forms.TextBox
        Friend WithEvents txtParagraphs As System.Windows.Forms.TextBox
        Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
        Friend WithEvents cmdFile As System.Windows.Forms.Button
        Friend WithEvents txtFile As System.Windows.Forms.TextBox
        Friend WithEvents txtChars As System.Windows.Forms.TextBox
        Friend WithEvents cmdExit As System.Windows.Forms.Button
        Friend WithEvents txtLength As System.Windows.Forms.TextBox
        Friend WithEvents lblTotal As System.Windows.Forms.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.lblChars = New System.Windows.Forms.Label
            Me.lblWords = New System.Windows.Forms.Label
            Me.lblSentences = New System.Windows.Forms.Label
            Me.lblParagraphs = New System.Windows.Forms.Label
            Me.txtChars = New System.Windows.Forms.TextBox
            Me.txtWords = New System.Windows.Forms.TextBox
            Me.txtSentences = New System.Windows.Forms.TextBox
            Me.txtParagraphs = New System.Windows.Forms.TextBox
            Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog
            Me.cmdFile = New System.Windows.Forms.Button
            Me.txtFile = New System.Windows.Forms.TextBox
            Me.cmdExit = New System.Windows.Forms.Button
            Me.txtLength = New System.Windows.Forms.TextBox
            Me.lblTotal = New System.Windows.Forms.Label
            Me.SuspendLayout()
            '
            'lblChars
            '
            Me.lblChars.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblChars.Location = New System.Drawing.Point(12, 20)
            Me.lblChars.Name = "lblChars"
            Me.lblChars.Size = New System.Drawing.Size(44, 16)
            Me.lblChars.TabIndex = 0
            Me.lblChars.Text = "Char #"
            '
            'lblWords
            '
            Me.lblWords.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblWords.Location = New System.Drawing.Point(12, 48)
            Me.lblWords.Name = "lblWords"
            Me.lblWords.Size = New System.Drawing.Size(52, 16)
            Me.lblWords.TabIndex = 1
            Me.lblWords.Text = "Words #"
            '
            'lblSentences
            '
            Me.lblSentences.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblSentences.Location = New System.Drawing.Point(184, 20)
            Me.lblSentences.Name = "lblSentences"
            Me.lblSentences.Size = New System.Drawing.Size(80, 16)
            Me.lblSentences.TabIndex = 2
            Me.lblSentences.Text = "Sentences #"
            '
            'lblParagraphs
            '
            Me.lblParagraphs.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblParagraphs.Location = New System.Drawing.Point(184, 48)
            Me.lblParagraphs.Name = "lblParagraphs"
            Me.lblParagraphs.Size = New System.Drawing.Size(80, 16)
            Me.lblParagraphs.TabIndex = 3
            Me.lblParagraphs.Text = "Paragraphs #"
            '
            'txtChars
            '
            Me.txtChars.Location = New System.Drawing.Point(72, 16)
            Me.txtChars.Name = "txtChars"
            Me.txtChars.Size = New System.Drawing.Size(88, 20)
            Me.txtChars.TabIndex = 4
            Me.txtChars.Text = ""
            '
            'txtWords
            '
            Me.txtWords.Location = New System.Drawing.Point(72, 44)
            Me.txtWords.Name = "txtWords"
            Me.txtWords.Size = New System.Drawing.Size(88, 20)
            Me.txtWords.TabIndex = 5
            Me.txtWords.Text = ""
            '
            'txtSentences
            '
            Me.txtSentences.Location = New System.Drawing.Point(288, 16)
            Me.txtSentences.Name = "txtSentences"
            Me.txtSentences.Size = New System.Drawing.Size(88, 20)
            Me.txtSentences.TabIndex = 6
            Me.txtSentences.Text = ""
            '
            'txtParagraphs
            '
            Me.txtParagraphs.Location = New System.Drawing.Point(288, 44)
            Me.txtParagraphs.Name = "txtParagraphs"
            Me.txtParagraphs.Size = New System.Drawing.Size(88, 20)
            Me.txtParagraphs.TabIndex = 7
            Me.txtParagraphs.Text = ""
            '
            'cmdFile
            '
            Me.cmdFile.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cmdFile.Location = New System.Drawing.Point(484, 20)
            Me.cmdFile.Name = "cmdFile"
            Me.cmdFile.Size = New System.Drawing.Size(96, 28)
            Me.cmdFile.TabIndex = 8
            Me.cmdFile.Text = "Analyze &File"
            '
            'txtFile
            '
            Me.txtFile.Location = New System.Drawing.Point(12, 136)
            Me.txtFile.Multiline = True
            Me.txtFile.Name = "txtFile"
            Me.txtFile.Size = New System.Drawing.Size(560, 164)
            Me.txtFile.TabIndex = 9
            Me.txtFile.Text = "TextBox1"
            '
            'cmdExit
            '
            Me.cmdExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cmdExit.Location = New System.Drawing.Point(484, 60)
            Me.cmdExit.Name = "cmdExit"
            Me.cmdExit.Size = New System.Drawing.Size(96, 28)
            Me.cmdExit.TabIndex = 10
            Me.cmdExit.Text = "&Exit"
            '
            'txtLength
            '
            Me.txtLength.Location = New System.Drawing.Point(116, 76)
            Me.txtLength.Name = "txtLength"
            Me.txtLength.Size = New System.Drawing.Size(44, 20)
            Me.txtLength.TabIndex = 15
            Me.txtLength.Text = ""
            '
            'lblTotal
            '
            Me.lblTotal.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lblTotal.Location = New System.Drawing.Point(4, 80)
            Me.lblTotal.Name = "lblTotal"
            Me.lblTotal.Size = New System.Drawing.Size(100, 16)
            Me.lblTotal.TabIndex = 14
            Me.lblTotal.Text = "Total File Length"
            '
            'frmReadaFile
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(592, 314)
            Me.Controls.Add(Me.txtLength)
            Me.Controls.Add(Me.lblTotal)
            Me.Controls.Add(Me.cmdExit)
            Me.Controls.Add(Me.txtFile)
            Me.Controls.Add(Me.cmdFile)
            Me.Controls.Add(Me.txtParagraphs)
            Me.Controls.Add(Me.txtSentences)
            Me.Controls.Add(Me.txtWords)
            Me.Controls.Add(Me.txtChars)
            Me.Controls.Add(Me.lblParagraphs)
            Me.Controls.Add(Me.lblSentences)
            Me.Controls.Add(Me.lblWords)
            Me.Controls.Add(Me.lblChars)
            Me.Name = "frmReadaFile"
            Me.Text = "Form1"
            Me.ResumeLayout(False)

        End Sub

    #End Region
        Private Sub cmdFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFile.Click
            Dim openFileDialog1 As New OpenFileDialog

            openFileDialog1.InitialDirectory = "c:\"
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            openFileDialog1.FilterIndex = 2
            openFileDialog1.RestoreDirectory = True

            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                'Place into Textbox
                txtFile.Text = StreamReaderReadFromFile(openFileDialog1.FileName)

                'Re-read file to count chars
                StreamReaderReadINCHARS(openFileDialog1.FileName)
            End If
        End Sub
        Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
            Me.Close()
        End Sub
        ' This subrouting uses a StreamReader object to open an existing file
        '   and read it character by character. It then outputs each character
        '   after a short pause, to show the user that the file is being read
        '   by characters. The output is added to the txtChars text box.
        Private Sub StreamReaderReadINCHARS(ByVal sFileName As String)
            Dim myStreamReader As StreamReader
            Dim myNextInt As Integer
            Dim iChar As Short
            Dim iWord As Short = 1
            Dim iPar As Short
            Dim iSentences As Short
            Dim iMisc As Short

            Try
                ' Create a StreamReader using a Shared (static) File class.
                myStreamReader = File.OpenText(sFileName)

                ' The Read() method returns an integer Decimal code for Char.
                myNextInt = myStreamReader.Read()
                ' The Read() method returns '-1' when the end of the
                '   file has been reached
                While myNextInt <> -1
                    Select Case myNextInt
                        Case 9                   'tab sapcing for Paragraphs
                            iPar += 1
                        Case 32                   'spaces
                            iWord += 1
                        Case 44                   'commas
                            iMisc += 1
                        Case 46                   'period
                            iSentences += 1
                        Case 48 To 57             'numbers
                            iChar += 1
                        Case 65 To 90, 97 To 122  'Letters
                            iChar += 1
                    End Select
                    'iCounter += 1
                    'txtChars.Text = iCounter
                    ' Read the next value from the Stream
                    myNextInt = myStreamReader.Read()
                End While
            Catch exc As Exception
                MsgBox("File could not be opened or read." + vbCrLf + _
                    "Please verify that the filename is correct, " + _
                    "and that you have read permissions for the desired " + _
                    "directory." + vbCrLf + vbCrLf + "Exception: " + exc.Message)
            Finally
                ' Close the object if it has been created.
                If Not myStreamReader Is Nothing Then
                    myStreamReader.Close()
                End If
                txtWords.Text = iWord.ToString
                txtChars.Text = iChar.ToString
                txtSentences.Text = iSentences.ToString
                txtParagraphs.Text = iPar.ToString
                txtLength.Text = (iChar + iWord + iSentences + iMisc + iPar).ToString
            End Try
        End Sub
        ' This subrouting uses a StreamReader object to open an existing file
        '   and read it in one pass and place the text in the txtFile text box.
        Public Function StreamReaderReadFromFile(ByVal sFileName As String)
            Dim myStreamReader As StreamReader
            Dim sData As String

            Try
                myStreamReader = File.OpenText(sFileName)
                ' Read the entire file in one pass, and add the contents to sData var.
                sData = myStreamReader.ReadToEnd()
            Catch exc As Exception
                MsgBox("File could not be opened or read." + vbCrLf + _
                    "Please verify that the filename is correct, " + _
                    "and that you have read permissions for the desired " + _
                    "directory." + vbCrLf + vbCrLf + "Exception: " + exc.Message)
            Finally
                ' Close the object if it has been created.
                If Not myStreamReader Is Nothing Then
                    myStreamReader.Close()
                End If
                StreamReaderReadFromFile = sData
            End Try
        End Function
    End Class


    'CLASS

    Option Strict On
    Option Explicit On

    Public Class StringProcessor
        'Hidden variables declared and set with initial values
        Private WordTotal As Integer = 0
        Private SentenceTotal As Integer = 0
        Private ParagraphTotal As Integer = 0
        Private CharacterTotal As Integer = 0
        'The following statements sets the properties
        'for the StringProcessor class
        Public ReadOnly Property Character() As Integer
            Get
                Return CharacterTotal
            End Get
        End Property
        Public ReadOnly Property Word() As Integer
            Get
                Return WordTotal 'value that is returned to application
            End Get
        End Property
        Public ReadOnly Property Sentence() As Integer
            Get
                Return SentenceTotal 'value that is returned to application
            End Get
        End Property
        Public ReadOnly Property Paragraph() As Integer
            Get
                Return ParagraphTotal 'value that is returned to application
            End Get
        End Property
        'The following Method counts the characters, words
        'sentences, and paragraphs of the file from the application
        Public Sub ProcessFile(ByVal path As String)
            'Local variable declared and set with initial values
            Dim c As Integer
            Dim LineNum As Integer = 0
            Dim NewParagraph As Boolean = True
            Dim NewSentence As Boolean = True
            Dim NewWord As Boolean = True
            Dim TxtFile As System.IO.StreamReader
            Dim FileContent As String

            Try
                TxtFile = New System.IO.StreamReader(path) 'File is opened
                FileContent = TxtFile.ReadToEnd 'Entire file is read
                'Each character is analyzed individually
                For c = 0 To FileContent.Length - 1
                    If (FileContent.Chars(c) = ControlChars.Cr) Then
                        'After a carriage return the count for a new
                        'word begins
                        LineNum += 1
                        NewWord = True
                        'If there are 2 or more carriage returns
                        'then a new paragraph begins
                        If (LineNum > 1) Then
                            NewParagraph = True
                        End If
                        'If a line consist entirely of spaces
                        'then the line count is not increased
                    ElseIf Not Char.IsControl(FileContent.Chars(c)) Then
                        If (FileContent.Chars(c)) <> "" Then
                            LineNum = 0
                        End If
                        'If we are on a new paragraph then the count is increased
                        If NewParagraph And (FileContent.Chars(c) <> "") Then
                            ParagraphTotal += 1
                            NewParagraph = False
                        End If
                        'If we are on a new word then the count is increased
                        If (FileContent.Chars(c) <> "") And NewWord Then
                            WordTotal += 1
                            NewWord = False
                        End If
                        ' A Period denotes a new sentence and increases the count
                        If (FileContent.Chars(c) = ".") Then
                            SentenceTotal += 1
                            'Two consecutive spaces denotes a new word
                        ElseIf (FileContent.Chars(c) = " ") Then
                            NewWord = True
                        End If
                        CharacterTotal += 1
                    End If
                Next c
                'Error Handling displays message when file
                'cannot be opened
            Catch ex1 As System.IO.IOException
                MsgBox(ex1.ToString)
            End Try
        End Sub
    End Class
    0
     
    LVL 27

    Expert Comment

    by:planocz
    forgot to change this line of code to ...

            Dim o As New StringProcessor.StringProcessor
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
    1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    934 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now