Random word from list

This commit is contained in:
2024-05-10 23:24:46 +03:00
parent 07aa15f7f5
commit 452d051f1f
2 changed files with 38 additions and 1 deletions

View File

@@ -1,2 +1,10 @@
# Random_word_from_list
# Random word from list
Это полезная программа, которая выбирает случайное слово из заданного списка.
Как запустить скрипт
```
python Random_word_from_list.py
```
Убедитесь, что у вас есть файл в том же каталоге, из которого вы хотите выбрать случайное слово.

29
Random_word_from_list.py Normal file
View File

@@ -0,0 +1,29 @@
import sys
import random
# check if filename is supplied as a command line argument
if sys.argv[1:]:
filename = sys.argv[1]
else:
filename = input("What is the name of the file? (extension included): ")
try:
file = open(filename)
except (FileNotFoundError, IOError):
print("File doesn't exist!")
exit()
# handle exception
# get number of lines
num_lines = sum(1 for line in file if line.rstrip())
# generate a random number between possible interval
random_line = random.randint(0, num_lines)
# re-iterate from first line
file.seek(0)
for i, line in enumerate(file):
if i == random_line:
print(line.rstrip()) # rstrip removes any trailing newlines :)
break