Results 1 to 20 of 20

Thread: Help with Text files

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    124

    Unhappy Help with Text files

    I am desperate for a simpler way to use OPENMODE.INPUT to access a text file.
    what I really want to do, is pick a random word from the text file. but pick
    a random word more than once. Can someone help me?

  2. #2
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Help with Text files

    I wasn't aware there was a complicated way?

    What exactly does the file consist of? A list of words, normal text?
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  3. #3
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Help with Text files

    Load the contents of the textfile into a string using a StreamReader. Separate that string using the String.Split method and store the random words into a general list(of string). Declare a new instance of the random class at the form level. Finally to pick a random word, use the Random.Next method setting the maximum value to the list's count.

    All in all it would look something like this:
    Code:
    Option Strict On
    Option Explicit On
    Public Class Form1
       Private r As New Random
       Private wordlist As New List(Of String)
    
       Private Sub Form_Load
          Dim sr As New IO.StreamReader(<file name here>)
          Dim str As String = sr.ReadToEnd
          sr.Close
    
          For Each itm As String in str.Split(<delimiter here>, StringSplitOptions.RemoveWhiteEntries)
             wordlist.Add(itm)
          Next
       End Sub
    
       Private Function rndWord() As String
          Dim int As Integer = r.Next(0, mylist.Count)
          rndWord = mylist.Item(int)
    
          Return rndWord
       End Function
    End Class
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  4. #4
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Help with Text files

    vb Code:
    1. Dim rng As New Random
    2. Dim words = IO.File.ReadAllLines("C:\words.txt")
    3. Dim word = (From n In words Order By rng.NextDouble).FirstOrDefaul

    Your last part is a little confusing. Do you mean you also want more then One word?

    vb Code:
    1. Dim rng As New Random
    2. Dim words = IO.File.ReadAllLines("C:\words.txt")
    3. Dim tenWords = words.OrderBy(Function(n) rng.NextDouble()).Take(10)
    Last edited by ident; Apr 2nd, 2013 at 01:21 PM.

  5. #5
    Hyperactive Member Vladamir's Avatar
    Join Date
    Feb 2012
    Location
    Miami, FL
    Posts
    486

    Re: Help with Text files

    As I used to be called Mr. Ascii because back in the 1980's era I wrote tons of code around reading and writing to text files, I was at first lost when I picked up VB.NET only a year ago to discover that all my old methods were no longer any good. I learned all about StreamReader and StreamWriter...but like lots of things with .NET there is more than one method of doing things. I did a search on the command on OPENMODE.INPUT and came across some methods that are very similar to the old way I used to read and write text files.

    In what you're describing it sounds like you'd want to use StreamReader and read the entire file into an object, then use the Random class to pick one or more of the items in your object and I think dday9 has that method outlined for you in his post.

  6. #6
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Help with Text files

    ReadToEnd returns a string containg the entire text of the file which you're reading and splitting it into lines. File.ReadAllLines returns a string array.

  7. #7
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    dday9 >>>

    I'm new to VB.NET and am using your code as a practice exercise. I had a problem with this line:

    Code:
    For Each itm As String In Str.Split(",", StringSplitOptions.RemoveWhiteEntries)
    It returns an error in VB 2012: "Error 1 'RemoveWhiteEntries' is not a member of 'System.StringSplitOptions'"

    Would you help me fix this code, so it will work? Also, myList is not declared in the class, so I changed the name of myList to WordList inside the RndWord() Function. Is that OK and will it work?

  8. #8
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Help with Text files

    Quote Originally Posted by CheeseWiZ View Post
    I'm new to VB.NET and am using your code as a practice exercise. I had a problem with this line:
    It returns an error in VB 2012: "Error 1 'RemoveWhiteEntries' is not a member of 'System.StringSplitOptions'"
    It was a typo, it's suppose to be RemoveEmptyEntries.
    Also, myList is not declared in the class, so I changed the name of myList to WordList inside the RndWord() Function. Is that OK and will it work?
    No it will not, unless you preform everything that I put in the form_load into the rndWord function which would be inefficient.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  9. #9
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    dday9 >>>

    Quote Originally Posted by dday9 View Post
    It was a typo, it's suppose to be RemoveEmptyEntries.
    Code:
    For Each itm As String In Str.Split(",", StringSplitOptions.RemoveEmptyEntries)
    Gives me a new error:

    Code:
    "Error	1	Overload resolution failed because no accessible 'Split' can be called with these arguments:
        'Public Function Split(separator() As String, options As System.StringSplitOptions) As String()': Value of type 'String' cannot be converted to '1-dimensional array of String'.
        'Public Function Split(separator() As Char, options As System.StringSplitOptions) As String()': Option Strict On disallows implicit conversions from 'String' to '1-dimensional array of Char'.
        'Public Function Split(separator() As Char, count As Integer) As String()': Option Strict On disallows implicit conversions from 'String' to '1-dimensional array of Char'.
        'Public Function Split(ParamArray separator() As Char) As String()': Option Strict On disallows implicit conversions from 'String' to 'Char'.
        'Public Function Split(ParamArray separator() As Char) As String()': 'System.StringSplitOptions' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit."
    Would you post a working code for this whole exercise?

    Sorry for jacking your thread supercell.

  10. #10
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Help with Text files

    If you have an issue please start your own thread. How ever as repeatedly said. You would not read a file into a string to split into an array.

  11. #11
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    Quote Originally Posted by ident View Post
    If you have an issue please start your own thread. How ever as repeatedly said. You would not read a file into a string to split into an array.
    Absolutely no help. Thanks for nothing.

  12. #12
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Help with Text files

    Wrap your comma in curly brackets:
    Code:
    For Each itm As String In Str.Split({","}, StringSplitOptions.RemoveEmptyEntries)
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  13. #13
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Help with Text files

    With that type of attitude you wont be getting much help here. The post was helpful it's just you do not understand it because you must be One of the unlucky Ones who can't access MSDN.

  14. #14
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    Quote Originally Posted by ident View Post
    With that type of attitude you wont be getting much help here. The post was helpful it's just you do not understand it because you must be One of the unlucky Ones who can't access MSDN.
    No, it's actually that instead of replying with any helpful examples like dday9, you choose to waste your efforts on being condescending toward someone who is new to VB.net.

  15. #15
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    Quote Originally Posted by dday9 View Post
    Wrap your comma in curly brackets:
    Code:
    For Each itm As String In Str.Split({","}, StringSplitOptions.RemoveEmptyEntries)
    I used your code, and put Messagebox.Show(RndWrd) inside of a button, and it indeed pops up with a random word everytime. Thanks so much for providing real help.

    For anyone else, this is the fixed code I used provided by dday9:

    Code:
    Option Strict On
    Option Explicit On
    
    Public Class Form1
        Private R As New Random
        Private Wordlist As New List(Of String)
    
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim SR As New IO.StreamReader("c:\test.txt")
            Dim Str As String = SR.ReadToEnd
            SR.Close()
    
            For Each itm As String In Str.Split({","}, StringSplitOptions.RemoveEmptyEntries)
                Wordlist.Add(itm)
            Next
        End Sub
    
        Private Function RndWrd() As String
            Dim int As Integer = R.Next(0, Wordlist.Count)
            RndWrd = Wordlist.Item(int)
    
            Return RndWrd
        End Function
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MessageBox.Show(RndWrd)
        End Sub
    End Class

  16. #16
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,398

    Re: Help with Text files

    Do you not understand the difference between a string and an array? dday9 example reads the file into a string. Then splits the file into an array. You would not do this. I have posted what to do above.

    Here is the code above that you can't seem to understand. dday9 example in Two lines. NOT creating a string to split into an Array.

    vb Code:
    1. Dim rng As New Random
    2. MessageBox.Show((From n In IO.File.ReadAllLines("C:\words.txt") Order By rng.NextDouble).FirstOrDefault())
    Last edited by ident; Apr 2nd, 2013 at 03:38 PM.

  17. #17
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    Quote Originally Posted by ident View Post
    Do you not understand the difference between a string and an array? dday9 example reads the file into a string. Then splits the file into an array. You would not do this. I have posted what to do above.

    Here is the code above that you can't seem to understand. dday9 example in Two lines. NOT creating a string to split into an Array.
    Again, condescending. Perhaps you're mad that your example was overlooked? I only bypassed your example because you didn't seem to understand the OP's request entirely. I understand an array is a container capable of holding multiple strings, where a single string is meant for holding just one variable. That's the best way I can describe it, as I'm new to VB.NET.

    You seem to be suggesting that your code is superior for the simple reason that it's smaller and doesn't need to create a string to split into an array to get the random word. Great. Thanks. This is more helpful than telling me I'm new and don't know how to access MSDN.



    vb Code:
    1. Dim rng As New Random
    2. MessageBox.Show((From n In IO.File.ReadAllLines("C:\words.txt") Order By rng.NextDouble).FirstOrDefault())
    [/QUOTE]

  18. #18
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,927

    Re: Help with Text files

    CheeseWiZ, stop being so hostile.

    While you might not like the posts ident has made, they are entirely for your benefit and they are not condescending. The worst ident is done is imply you should drop the attitude, and that was explicitly in response to you being rude (therefore good advice for your benefit).

    Just like with people of any skill level, there will be parts of posts that you don't understand (especially when some bits are 'unspoken'), but that is a reason to ask for clarification, not for attacking the person who made the post.


    A very important point raised above is that you should not hijack peoples threads. There are a variety of reasons for that, one of the most important being that you are almost certainly reducing the help that the original poster will get (and as they started the thread, that is rude).

    As such, please start your own thread if you want to discuss this code any further.

    If you want to discuss my post or any of ident's, send a private message to me or another moderator.

  19. #19
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Help with Text files

    When replying to a thread always try to be as polite as possible. If you feel offended by a reply either read it again as if the poster didn't mean to offend you and give a nice reply back or report the post and let us moderators handle it but do not post another angry, condescending reply by telling that person how condescending they are.

    It's never OK to hijack someone else's thread however in this case there was no hijacking going on. All I saw was a follow up question on an answer. It's OK to post follow up questions to answers given even in other peoples threads as long as it's on the exact same subject. So telling someone to create their own thread when they have problems with posted code in this thread is just silly. Especially since the problem was that the code posted was buggy or wrong, in this case because of a typo (things like that happens sometimes when you write the code directly in the reply without actually trying it out. It happens to me all the time ).

    Quote Originally Posted by ident View Post
    How ever as repeatedly said. You would not read a file into a string to split into an array.
    Why not? If I want to split up some text I can obviously only do that after I have the text. What if I would want to pick a random text file and select a random word from that? ReadAllLines returns an array of text lines, not an array of words or an array of some other tokens I might want to have. Your code is pretty neat but will only work if there is only a single word on each line and no empty lines in the file.

    I'm curious though, why call NextDouble on the Random object instead of Next? The indices in an array are after all expressed in integers not in a double precision floating point number.

  20. #20
    Lively Member CheeseWiZ's Avatar
    Join Date
    Mar 2013
    Posts
    71

    Re: Help with Text files

    Quote Originally Posted by Joacim Andersson View Post
    It's never OK to hijack someone else's thread however in this case there was no hijacking going on. All I saw was a follow up question on an answer. It's OK to post follow up questions to answers given even in other peoples threads as long as it's on the exact same subject. So telling someone to create their own thread when they have problems with posted code in this thread is just silly. Especially since the problem was that the code posted was buggy or wrong, in this case because of a typo (things like that happens sometimes when you write the code directly in the reply without actually trying it out. It happens to me all the time ).
    Thanks. I didn't feel like my question was off-target from the OP's goal, and therefore felt it might be helpful to the OP and myself to ask dday9 if he would provide help with his suggestion. Being told to start my own thread after I had already apologized to the OP just felt like an unnecessary slap for being new. Regardless, it's in the past and I have no ongoing issue with ident or anyone else. My apologies.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width