Answer the question
In order to leave comments, you need to log in
How to properly split a string?
There is such a code. Let's say the user sent us "choose 1 or 2". Everything works, the bot selects one option, but as soon as the user increases the number of words in the option, the bot does not work correctly (selects the word "or" or only part of the option). How to properly split a string? If we make the word "or" as a separator, then how to exclude the word "choose" from the first option so that the bot does not send us "I choose choose 1"
If it is impossible, then how to replace it?
text = event.obj['text'].split(' ')
if text[0] == "Выбери" or text[0] == "выбери":
list = [text[1], text[3]]
change = random.choice(list)
vk.method("messages.send",
{
"chat_id": event.object.peer_id - 2000000000,
"message": "Я выбираю " + f'{change}',
"random_id": random.randint(1, 2147483647)
})
Answer the question
In order to leave comments, you need to log in
I thought a little and shared. If anyone needs
text_1 = event.obj['text'].split(' ', maxsplit=1)
if text_1[0] == "Выбери" or text_1[0] == "выбери":
text_2 = text_1[1].split('или')
list = [text_2[0], text_2[1]]
change = random.choice(list)
vk.method("messages.send",
{
"chat_id": event.object.peer_id - 2000000000,
"message": "Я выбираю " + f'{change}',
"random_id": random.randint(1, 2147483647)
})
No way.
Threat only require a more or less strict input format from the user.
Use regular expressions as an option:
import re
import random
if "выбери" in event.obj['text'].lower():
variants_list = re.findall('\d+', event.obj['text'])
if 'или' in event.obj['text'].lower():
change = random.choice(variants_list)
...
>>> stop_words = ['выбери', 'или']
>>> input_text_list = input_text.split()
>>> target_words_list = [word for word in input_text_list if word.lower() not in stop_words]
list =
if text[0] == "Choose" or text[0] == "choose":
if text[0].lower() == "выбери":
You can split a string using the work method.
WITH strings In particular, the split method Designed to work with lists.
having a list
xx = ['1;2;3;4']
text.split(';')
text = list.
split() method
';' character between lines.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question