PDA

Просмотр полной версии : фразы в txt


wefwefwefwef
14.02.2022, 00:15
как сделать так что-бы мой бот брал фразы из txt рандомно?

chapo
14.02.2022, 00:39
Python:






import
random
def
getRandomLineFromFile
(
file
)
:
list
=
[
]
iofile
=
open
(
file
,
'r'
)
lines
=
iofile
.
readlines
(
)
for
line
in
lines
:
list
.
append
(
line
)
iofile
.
close
(
)
random
.
seed
(
)
return
list
[
random
.
randint
(
0
,
len
(
list
)
-
1
)
]
print
(
getRandomLineFromFile
(
'ПУТЬ К ФАЙЛУ'
)
)




https://forum.antichat.xyz/attachments/27974906/img_2abd7fefc0.png

NoN4m3
14.02.2022, 01:59
Python:






import
random
def
getRandomLineFromFile
(
filepath
)
:
with
open
(
filepath
)
as
f
:
lines
=
f
.
readlines
(
)
return
lines
[
random
.
randint
(
0
,
len
(
lines
)
-
1
)
]
filepath
=
"default.txt"
print
(
getRandomLineFromFile
(
filepath
)
)

laiser
14.02.2022, 14:04
Python:






import
random
def
getRandomLineFromFile
(
filepath
)
:
with
open
(
filepath
)
as
f
:
lines
=
f
.
readlines
(
)
return
lines
[
random
.
randint
(
0
,
len
(
lines
)
-
1
)
]
filepath
=
"default.txt"
print
(
getRandomLineFromFile
(
filepath
)
)





А почему ты не использовал random.choice() ?

NoN4m3
14.02.2022, 14:05
А почему ты не использовал random.choice() ?


не знал об этой функции 😀

pomidorq
14.02.2022, 20:20
Python:






import
random
def
get_random_line
(
filename
)
:
try
:
with
open
(
str
(
filename
)
,
"r"
)
as
file
:
_
=
file
.
readlines
(
)
string
=
random
.
choice
(
_
)
.
strip
(
)
return
string
except
FileNotFoundError
:
return
-
1
result
=
get_random_line
(
"smth.txt"
)
if
result
!=
-
1
:
print
(
result
)
else
:
print
(
"Такого файла не существует."
)