How to choose and display a random word from an external txt file?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Taabta

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?

:bust_in_silhouette: Reply From: Eric Ellingson

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(".", "")
	
	print(words)
	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]"

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?
EDIT:
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)
print(random_word)

EDIT2:
Needed to split(“\n”). now I get only one word. Also I put randomize() on top of get_random_world_from_file method to get a different word every time.

dancaer69 | 2021-02-07 16:07