Python - Selection of a specific number of words from the list submitted



  • Before he asked how to keep his words in the file, the odd questions were received, but not the xD.

    Anyway, let's say I have a file of words.txt, and it has a list of different words. I need to pick an undetermined number of early words from this list. The words are recorded as follows:

    привет
    как
    дела
    это
    пример
    

    Of course they're bigger, but the point is clear. There's got to be an undetermined number, I think through random.randint (5, 35). How do you do that? Cycles and all that bad know, so there's no idea.



  • How can we try this:

    import random
    

    file = "FILE_PATH"
    words = []
    random_words = []
    num = random.randint(1, 5) # рандомное число
    with open(file, "r") as f:
    for line in f:
    words.append(line) # добавляем свои слова в список

    for i in set(random.choices(words, k=num)):
    random_words.append(i) # добавляем рандомные слова в список

    newString = " ".join([line.rstrip() for line in random_words]
    print(newString) # строка для отправки


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2