ANTICHAT

ANTICHAT (https://forum.antichat.xyz/index.php)
-   Общие вопросы программирования (https://forum.antichat.xyz/forumdisplay.php?f=206)
-   -   фразы в txt (https://forum.antichat.xyz/showthread.php?t=1422191)

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/attachmen...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

Цитата:

Сообщение от NoN4m3

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

Цитата:

Сообщение от laiser

А почему ты не использовал 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
(
"Такого файла не существует."
)



Время: 08:54