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?
Printable View
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?
I wasn't aware there was a complicated way?
What exactly does the file consist of? A list of words, normal text?
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
vb Code:
Dim rng As New Random Dim words = IO.File.ReadAllLines("C:\words.txt") 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:
Dim rng As New Random Dim words = IO.File.ReadAllLines("C:\words.txt") Dim tenWords = words.OrderBy(Function(n) rng.NextDouble()).Take(10)
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.
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.
dday9 >>>
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'"Code:For Each itm As String In Str.Split(",", StringSplitOptions.RemoveWhiteEntries)
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?
It was a typo, it's suppose to be RemoveEmptyEntries.
No it will not, unless you preform everything that I put in the form_load into the rndWord function which would be inefficient.Quote:
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?
dday9 >>>
Gives me a new error:Code:For Each itm As String In Str.Split(",", StringSplitOptions.RemoveEmptyEntries)
Would you post a working code for this whole exercise?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."
Sorry for jacking your thread supercell.
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.
Wrap your comma in curly brackets:
Code:For Each itm As String In Str.Split({","}, StringSplitOptions.RemoveEmptyEntries)
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.
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
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:
Dim rng As New Random MessageBox.Show((From n In IO.File.ReadAllLines("C:\words.txt") Order By rng.NextDouble).FirstOrDefault())
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.
[/QUOTE]vb Code:
Dim rng As New Random MessageBox.Show((From n In IO.File.ReadAllLines("C:\words.txt") Order By rng.NextDouble).FirstOrDefault())
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.
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 :)).
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.
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.