Сокращение кода открытия файлов Python
Мне нужно сократить код:
@my_bot.message_handler(content_types='text')
def get_text(message):
str_1 = 'привет'
txt_1 = random.choice(list(open('answer1.txt', 'r', encoding='utf-8')))
str_2 = 'как дела'
txt_2 = random.choice(list(open('answer2.txt', 'r', encoding='utf-8')))
str_3 = 'что делаешь'
txt_3 = random.choice(list(open('answer3.txt', 'r', encoding='utf-8')))
str_4 = 'расскажи интересный факт'
txt_4 = random.choice(list(open('answer4.txt', 'r', encoding='utf-8')))
str_5 = 'не устал работать'
txt_5 = random.choice(list(open('answer5.txt', 'r', encoding='utf-8')))
text_1 = set(str_1.split())
text_2 = set(str_2.split())
text_3 = set(str_3.split())
text_4 = set(str_4.split())
text_5 = set(str_5.split())
inp = set(set(message.text.lower().split()))
if inp & text_1:
my_bot.send_message(message.chat.id, txt_1)
elif inp & text_2:
my_bot.send_message(message.chat.id, txt_2)
elif inp & text_3:
my_bot.send_message(message.chat.id, txt_3)
elif inp & text_4:
my_bot.send_message(message.chat.id, txt_4)
elif inp & text_5:
my_bot.send_message(message.chat.id, txt_5)
У меня получилось так:
@my_bot.message_handler(content_types='text')
def get_text(message):
txt_1 = random.choice(list(open('answer1.txt', 'r', encoding='utf-8')))
f1 = set('привет')
f2 = set('как дела')
f3 = set('что делаешь')
f4 = set('расскажи интересный факт')
f5 = set('не устал работать')
inp = set(set(message.text.lower()))
if inp & f1:
my_bot.send_message(message.chat.id, txt_1)
elif inp & f2:
my_bot.send_message(message.chat.id, txt_1)
elif inp & f3:
my_bot.send_message(message.chat.id, txt_1)
elif inp & f4:
my_bot.send_message(message.chat.id, txt_1)
elif inp & f5:
my_bot.send_message(message.chat.id, txt_1)
Помогите, пожалуйста, как можно сократить код открытия файлов?
txt_1 = random.choice(list(open('answer1.txt', 'r', encoding='utf-8')))
txt_2 = random.choice(list(open('answer2.txt', 'r', encoding='utf-8')))
txt_3 = random.choice(list(open('answer3.txt', 'r', encoding='utf-8')))
txt_4 = random.choice(list(open('answer4.txt', 'r', encoding='utf-8')))
txt_5 = random.choice(list(open('answer5.txt', 'r', encoding='utf-8')))
Ответы (1 шт):
Автор решения: n1tr0xs
→ Ссылка
- Вы не сократили, а вот что сделали:
str_3 = 'что делаешь'
text_3 = set(str_3.split()) # {'что', 'делаешь'}
f3 = set('что делаешь') # {'е', ' ', 'ч', 'о', 'а', 'ь', 'ш', 'т', 'л', 'д'}
Чтобы сократить нужно писать так:
f3 = set('что делаешь'.split())
- Чтобы сократить обращения к файлам - вынесите это в отдельную функцию:
def choice_from_file(path):
with open(path, 'r', encoding='utf-8') as file:
choice = random.choice(list(file))
return choice
txt_1 = choice_from_file('answer1.txt')
set(set(...)) - бесполезная конструкция. одного set всегда достаточно.