0 votes

hello all,
i want to know how to code for choosing a random word from an external text file(.txt) if that's possible, and how to display it by a RichTextLabel?

in Engine by (38 points)

1 Answer

+1 vote
Best answer

It's hard to say exactly without knowing what the external file looks like, but I'll try to make it generic enough.

func load_file(file_path):
    var file = File.new()
    file.open(file_path, file.READ)
    var text = file.get_as_text()
    return text

func get_random_word_from_file(file_path):
    var text = load_file(file_path).strip_edges()
    var words = text.split(" ")
    for i in range(words.size()):
        # here you can add whatever you want to remove
        # any unwanted characters
        words[i] = words[i].replace(",", "")
        words[i] = words[i].replace(".", "")

    return words[randi() % words.size()]

Then call it like:

var random_word = get_random_word_from_file("res://path/to/file.txt")
$RichTextLabel.text = random_word
# or if you're using bbcode
$RichTextLabel.bbcode_text = "[center]" + random_word + "[\center]"
by (1,656 points)
selected by

I'm new in godot and gdscript and trying to recreate a python word game. I have a txt file with one word on every line. The file is quit large, has abour 30000 words.
I tried the answer and I always get an empty list [].
Any help?
Sorry, I was typed the path wrong. I didn't get an error, so I thought that was right.
But with the correct path now all words printed and not one random:

func _ready():
var random_word = get_random_word_from_file(file_path)

Needed to split("\n"). now I get only one word. Also I put randomize() on top of getrandomworldfromfile method to get a different word every time.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.