Neculai Fantanaru

Everything Depends On The Leader

Метод Python Shuffle (): как смешивать слова в случайном порядке

On May 05, 2021
, in
Python Scripts Examples by Neculai Fantanaru

Полный код можно просмотреть здесь: https://pastebin.com/QR0Wky4j

Установите Python. Затем установите следующие две библиотеки с помощью интерпретатора командной строки (cmd) в Windows10: Обычно эти библиотеки уже включены в Python.

py -m pip install re
py -m pip install random

«Python Random»; код автоматически смешает слова в нужных вам предложениях, используя метод shuffle().

Option 1 - Simple Version

import random
import re # import for regular expressions

listOfStrings = ["Ana are mere", "Ana are pere", "Eu am mure"]
for s in listOfStrings: # for each s in the list I go through, I do something, and that something is in the body of the forum
   print(re.split(r' ', s)) # what is obtained after dividing a string by " " (space)
   result = re.split(r' ', s) # we save the result in a variable (the variable is a memory area where something is stored)
   random.shuffle(result) #
   print(result)

Option 2 - Saved Version

# extract the words directly from all the sentences with the help of a regular expression
mix = r"[a-zA-Z]+"
listOfWords = re.findall(mix, "To provide you with the best experiences, we and our partners use technologies. Such as cookies to store and / or access information. It is all about the device used.")
print("Result: ", listOfWords)
random.Random(4).shuffle(listOfWords)
print("Shuffled stuff: ", listOfWords)
# The first method to combine values from a list
finalString = "" # we initialize the variable in which the final text will be put with the string empty => does not contain anything
for cuvant in listOfWords: # FOR repeats what is in his body (what is in the bottom line)
   finalString = finalString + cuvant + " "
finalString = finalString.strip()
print(finalString)
#SAve
with open("shuffle-words.txt", "w") as some_file_handle:
   some_file_handle.write(finalString)

Option 3 - Saved Version (+ input pop-up window)

import re
import random
def shuffle_Bebe(text):
   regex = r"[a-zA-Z]+"
   listOfWords = re.findall(regex, text)
   random.shuffle(listOfWords)
   return listOfWords
def concatenate_Bebe(listOfWords): # concatenates a list of words and the returned result is a text
   finalString = "" # we initialize the variable in which the final text will be put with the string empty => does not contain anything
   for cuvant in listOfWords: # FOR repeats what is in his body (what is in the bottom line)
       finalString = finalString + cuvant + " "
   finalString = finalString.strip()
   return finalString
def save_text(cale_fisier, text):
   with open(cale_fisier, "w", encoding = 'utf-8') as file:
       file.write(text)
if __name__ == "__main__":
   print("Enter a word: ")
   text = str(input()) # you see the text box that is started at the input () command, and what you type in the box will be converted to a string with the str () command
   shuffled_list = shuffle_Bebe(text) # save the list of words that were shuffled
   print("Lista de cuvinte amestecate este: ", shuffled_list)
   text_final = concatenate_Bebe(shuffled_list)
   print("Textul obtinut din lista de mai sus este: ", text_final)
   save_text("c:\\Folder2\\test_final.txt", text_final)

Option 3 - Saved Version (+ input pop-up window) + Open File and Save File

import re
import random
def shuffle(text): 
   regex = r"[a-zA-Z]+" 
   listOfWords = re.findall(regex, text) 
   random.shuffle(listOfWords) 
   return listOfWords 
def concatenate(listOfWords): 
   finalString = "" 
   for cuvant in listOfWords: 
       finalString = finalString + cuvant + " "
   finalString = finalString.strip() 
   return finalString 
def read_text_from_file(cale_fisier):
   f = open(cale_fisier, "r") 
   text = f.read() 
   print("ce am citit: ", text)
   return text 
def save_text_into_file(cale_fisier, text):
   f = open(cale_fisier, "w", encoding = 'utf-8') 
   print("Ce am scris: ", text)
   f.write(text) 
text = read_text_from_file("test_final.txt")
lista_cuvinte_amestecate = shuffle(text)
text_final = concatenate(lista_cuvinte_amestecate)
save_text_into_file("test_final.txt", text_final)

Вы можете легко сделать то же сочетание слов с помощью PowerShell:< ! -- HTML-код, созданный с помощью hilite.me -->

 ((Get-Content -Path C:\Folder1\file.txt -Raw ) -split "\s+" | 
    Sort-Object {Get-Random} ) -join ' ' |
        Out-File -FilePath C:\Folder1\NewFile.txt

That's all folks.

If you like my code, then make me a favor: translate your website into Romanian, "ro".

Также ознакомьтесь с этой ВЕРСИЕЙ 2 или ВЕРСИЯ 3 или ВЕРСИЯ 4 или ВЕРСИЯ 5 или ВЕРСИЯ 6 или ВЕРСИЯ 7

Alatura-te Comunitatii Neculai Fantanaru
63 величайших качества лидера
Cele 63 de calităţi ale liderului

Зачем читать эту книгу? Потому что это имеет решающее значение для оптимизации вашей производительности. Потому что раскрывает основные координаты, после чего строят характер и навыки лидеров, подчеркивая, что им важно для повышения своего влияния.

Лидерство – магия мастерства
Atingerea maestrului

Существенной характеристикой этой книги по сравнению с другими книгами, представленными на рынке в той же области, является то, что она описывает на примерах идеальные компетенции лидера. Я никогда не утверждал, что стать хорошим лидером легко, но если люди будут...

Мастерское прикосновение
Leadership - Magia măiestriei

Для некоторых лидеров «руководство» больше напоминает шахматную игру, игру ума и проницательности; для других это означает азартную игру, игру, которую, как они думают, они могут выиграть каждый раз, рискуя и ставя все на одну карту.

Загадка лидерства
Leadership Puzzle

Я написал эту книгу, которая простым способом соединяет личностное развитие с лидерством, как пазл, где нужно соединять все данные кусочки, чтобы составить общий образ.

Руководство
Leadership - Pe înţelesul tuturor

Цель этой книги — предоставить вам информацию на конкретных примерах и показать, как обрести способность заставить других смотреть на вещи под той же точкой зрения, что и вы.

Лидерство для чайников
Leadership - Pe înţelesul tuturor

Не считая это согласием, книга представляет собой попытку обычного человека - автора - который простыми словами, фактами и обычными примерами вселяет в обычного человека смелость и оптимизм в его собственном стремлении быть хозяином самому себе и кто знает. ..может даже лидер.