Random word from list
This commit is contained in:
10
README.md
10
README.md
@@ -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
29
Random_word_from_list.py
Normal 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
|
||||
Reference in New Issue
Block a user