Labas, Pasauli!

Eilučių formatavimas

VP
Vilius P.
2024-07-09

Šitoje pamokoje skirsime dėmesį eilutės (string) tipo kintamiesiems. Sužinosime, kaip suformatuoti ir įterpti bet kokį kintamąjį į bet kurią eilutės vietą.

Sąvokos

Dvi pagrindinės sąvokos, be kurių reikšmių čia neapsieisime:

  1. Formatavimas. VLKK siūlo neblogus atitikmenis šiam tarptautinam žodžiui: formuotė arba formavimas. Formatavimu laikysime būdą išdėstyti tekstą;
  2. Interpoliacija. Įterpiamas kažko kito į jau esamą dalyką - šiuo atveju kintamųjų įterpimas į tekstą. Kadangi čia tinklapis apie mokslą, tai interpoliacija dar yra metodas suskaičiuojant trūkstamas reikšmes skaičių sekoje, naudojamas duomenų moksle.

Naudojimo atvejai

Kuo toliau į programavimo mišką, tuo daugiau reikia naudoti eilučių tipo kintamųjų formatavimą.

Šiame puslapyje, kuriame esate viršuje (priklausomai nuo naršyklės) puslapio adresas sudarytas naudojantis interpoliacija ir formatavimu. Adresai internete (URL) sudaryti iš skirtingų dalių:

  • Schemos (angl. scheme) https;
  • Domeno (angl. domain) pygame.kugelis.eu;
  • Kelio (angl. path) basics/start/strings_formatting;
  • ir kt.

Kitose vietose galite rasti pateiktą detalesnį skirstymą. Domenas ir schema sukonfigūruota automatiškai, kuriant tinklapius kelio sudarymą dažnai reikia formatuoti. Supaprastinus sudarymo principą galimą suprogramuoti taip:

.py
# In programming, these 3 variables come from functions dynamically depending on the page you are on 
chapter="basics"
subchapter="start"
tutorial="strings_formatting"
route=f"{chapter}/{subchapter}/{tutorial}"
print(route)

Kodo pavyzdyje panaudota f-string sintaksė, kurią išsaiškinsime vėliau. Dabar galite išbandyti ir pažiūrėti rezultatą tokios sintaksės.

Taip pat, dažnai prisijungus į tinklapius galima pamatyti pasisveikinimo žinutę, kurioje nurodytas jūsų vardas. Vardas dažnai gaunamas iš duomenų bazės, o žinutė suformatuojama tinklalapyje.

.py
name="Vilijus" # Imagine that this variable is retrieved from the database
greeting_message=f"Hello, {name}"
print(greeting_message) # Instead of printing, it would be shown on the page in a website

arba galima padaryti pasisveikiną, pagal esamą dienos metą:

.py
name="Vilijus"
greeting_message=""

# Time could be retrieved dynamically, but for simplicity, we made it constant
current_time = 14 # hours
if current_time >= 5 and current_time < 11:
    greeting_message=f"Good morning, Sir {name}"
elif current_time >= 11 and current_time < 20:
    greeting_message=f"Good day, Sir {name}"
else:
    greeting_message=f"Good evening, Sir {name}"

print(greeting_message)

Seniau, buvo paplitusi sukčiavimo schema, kai žmonėms atsiųsdavo laiškus į el. pašto dėžutės, kad šie pervestų pinigų tariamam nigerijos princui (daugiau apie tai skaitykite knowyourmeme). Galima sudaryti jį įdėjus vardą į tą laišką:

.py
name="Potential victim"
email_text = f"""
Subject: Urgent Assistance Required

Dear {name},

I am Prince Adebayo Olufemi of Nigeria. I need your help to transfer $20,000,000 out of the country. 
You will receive 30% ($6,000,000) for your assistance.

Please provide the following details:
1. Full name
2. Contact address
3. Phone number
4. Bank name and address
5. Bank account number and SWIFT code

Please keep this matter confidential. Time is of the essence. Awaiting your prompt response.

Best regards,
Prince Adebayo Olufemi
"""

print(email)

Šitame pavyzdyje panaudotas daugelio eilučių eilutės kintamasis. Naudojantis trimis kabutėmis eilutės kintamąjį galima užrašyti keliomis eilutės. Daugiau apie tai skaitykite w3school.

Sintaksė ir galimybės

Formatuotos eilutės su interpoliacija prirašant prieš kabučių „f“ Python kalboje vadinasi f-string. Yra ir kitų formatavimo būdu, bet f-string užtektinai funkcionalus, o be to, jis lengvai skaitomas. Kitus būdus rasite skyriuje Kiti formatavimo būdai.

Kaip ir minėta, norint panaudoti interpoliacija tiesiog reikės prirašyti f raidę prie atidaromųjų kabučių, o kintamuosius įdėti į figūrinius skliaustus:

.py
age=25
f_string=f"I am {age} years old"
print(f_string)

Aišku galima tokias eilučių reikšmes panaudoti tiesiogiai print funkcijoje:

.py
age=25
print(f"I am {age} years old")

Figūriniuose skliaustuose galima atlikti ir veiksmus

.py
a=5
b=10
print(f"{a}+{b}={a+b}")

Skaičių formatavimas

Toliau sužinosime, kaip galima modifikuoti skaičius. Šių dalykų nėra būtina mokėti mintinai (nebent jums atsiskaitymas), visada galite juos pasižiūrėti internete, bet turite žinoti, kokios galimybės egzistuoja.

Skaičių kiekis po kablelio

Jeigu turime skaičių, kuris turi daug skaičių po kablelio ir norėsime nusikratyti jų ir palikti tik kelis skaičius po kablelio, tai galėsim padaryti taip:

.py
approximate_pi = 22/7
print(f"{approximate_pi:.4f}") # prints: 3.1429

Po : nurodomas modifikatorius (angl. modifier). Skaičius su tašku (šiuo atveju .4) nurodo, kad skaičių reprezentuosime su 4 skaičiais po kablelio. Raidė f nurodo, kad šį skaičių laikysime slankiojo kablelio skaičiumi (angl. float).

Tokiu būdu galima apvalinti skaičius iki norimo tikslumo:

.py
value = 3.45123951923
print(f"{value:.1f}") # prints: 3.5

O kaip ir minėta anksčiau, reikšmes ar reiškinius galima rašyti tiesiai į figūrinius skliaustus:

.py
print(f"{3+0.45123951923:.1f}") # prints: 3.5

Eksponentinė (standartinė) išraiška

Dirbant su dideliais arba labai mažais skaičiais, reikalinga standartinė išraiška.

Matematikoje standartinė išraiška yra skaičius pavidalu , kur , o sveikasis skaičius.

Tarkime turime skaičių , tai yra tas pats skaičius skaičius, bet standartinės išraiškos pavidalu.

Python kalboje ir kitose kompiuterių technologijose ši išraiškos pavidalos šiek tiek kitoks. Skaičius būtų užrašytas 1.250000e+05. Tai galite išbandyti paleidę šį kodą:

.py
print(f"{125000:e}") # prints: 1.250000e+05

Tokius skaičius ir galima pateikti tik su keleta skaičių po kablelio:

.py
print(f"{125000:.2e}") # prints: 1.25e+05

# Line below will print number in non-scientific notation 
print(f"{126000:.1e}") # prints: 1.2e+05

Kiti modifikatoriai

Kartais programuojant reikia skaičius iš vienos skaičiavimo sistemos paversti į kitą (iš dešimtainės į dvejatainę, iš dešimtainės į šešioliktainę ir kt.). Python kalboje skaičių paversti iš dešimtainės skaičiavimo sistemas į kitas yra sukurti b, o, x modifikatoriai:

.py
number=15
print(f"decimal {number} in binary is equal to {number:b}") # prints: decimal 15 in binary is equal to 1111
print(f"decimal {number} in octal is equal to {number:o}") # prints: decimal 15 in octal is equal to 17
print(f"decimal {number} in hexadecimal is equal to {number:x}") # prints: decimal 15 in hexadecimal is equal to f 

another_number = 2025
print(f"decimal {another_number} in binary is equal to {another_number:b}") # prints: decimal 2025 in binary is equal to 11111101001
print(f"decimal {another_number} in octal is equal to {another_number:o}") # prints: decimal 2025 in octal is equal to 3751
print(f"decimal {another_number} in hexadecimal is equal to {another_number:x}") # prints: decimal 2025 in hexadecimal is equal to 7e9

Taip pat yra modifikatorius paversti skaičiui į procentus (atkreipkite į pirmąjį print ir sekančius, bei išvesties tekstą):

.py
first_number=0.5
print(f"{first_number} is equal to {first_number:%}") # prints: 0.5 is equal to 50.000000%

second_number=0.01
print(f"{second_number} is equal to {second_number:.2}") # 0.01 is equal to 1.00%

third_number=0.999
print(f"{third_number} is equal to {third_number:.1%}") # 0.99 is equal to 99.00%

fourth_number=1
print(f"{fourth_number} is equal to {fourth_number:.0%}") # 1 is equal to 100.00%

Plotis ir lygiavimas

Formatuojant reikšmes su Python (ir dažnai kitomis kalbomis) galima nustatyti, kiek simbolių vietų užims eilutės reikšmė. Dar galima sakyti, kad eilutės reikšmei suteikiamas plotis. Toliau du pavyzdžiai, pirmajame tekstas pateiktas nesuteikus jam papildomos vietos, o kitas - suteikus.

.py
# In future you will learn how to make it more readable and less clunky
name_1="Alice"
position_1="Software engineer"
age_1=19
salary_1=1200

name_2="Bob"
position_2="Teacher"
age_2=25
salary_2=990

name_3="Charlie"
position_3="Data analyst"
age_3=26
salary_3=2790


# Header row
print("Name Position Age Salary")

# Data rows
print(f"{name_1} {position_1} {age_1} {salary_1}")
print(f"{name_2} {position_2} {age_2} {salary_2}")
print(f"{name_3} {position_3} {age_3} {salary_3}")

# Outputs:
# Name Position Age Salary
# Alice Software engineer 19 1200
# Bob Teacher 25 990
# Charlie Data analyst 26 2790

Gauta lentelė netvarkinga, nestruktūrizuota. Tam, kad sutvarkytume, galima priskirti kiekvienai (įskaitant ir lentelės antraštinės eilės) reikšmei jos plotį. Toliau kode nėra kartojimas kintamųjų sukūrimas

.py
# ...
# The same variables as in the earlier example

# Header row
print(f"{'Name':10} {'Position':18} {'Age':8} {'Salary':8}")

# Data rows
print(f"{name_1:10} {position_1:18} {age_1:8} {salary_1:8}")
print(f"{name_2:10} {position_2:18} {age_2:8} {salary_2:8}")
print(f"{name_3:10} {position_3:18} {age_3:8} {salary_3:8}")

# Outputs:
# Name       Position           Age      Salary  
# Alice      Software engineer        19     1200
# Bob        Teacher                  25      990
# Charlie    Data analyst             26     2790

Dabar tekstui suteiktas fiksuotas plotis, bet babar atsirado kita problema, skaičiai sulygiuoti pagal dešinį kraštą. Lygiavimą galima nurodyti pridėję lygiavimo simobolį prie pločio reikšmės. Jų yra trys

  • < lygiavimas kairėje;
  • > lygiavimas dešinėje;
  • ^ lygiavimas centre;

Pagal nutylėjimą, eilutės reikšmės lygiuojamos kairėje, skaičiai dešinėje - taip, kaip matome ankstenio kodo išvestyje.

Sutvarkykime kodą ir sulygiuokime reikšmes, kad lentelė būtų tvarkinga: pirmasis stulpelis bus lygiuojamas palei kairį šoną, o kiti pagal dešinįjį.

.py
# ...
# The same variables as in the earlier example

# Header row
print(f"{'Name':<10} {'Position':>18} {'Age':>8} {'Salary':>8}")

# Data rows
print(f"{name_1:<10} {position_1:>18} {age_1:>8} {salary_1:>8}")
print(f"{name_2:<10} {position_2:>18} {age_2:>8} {salary_2:>8}")
print(f"{name_3:<10} {position_3:>18} {age_3:>8} {salary_3:>8}")

# Outputs:
# Name                 Position      Age   Salary
# Alice       Software engineer       19     1200
# Bob                   Teacher       25      990
# Charlie          Data analyst       26     2790

Dabar lentelė atrodo padoriau. Kituose skyriuose dar labiau patobulinsime ją.

Jeigu tekstas užima mažiau vietos negu nurodyta, tai tuščia vieta užpildoma tarpais. Jeigu norime užpildyti kitu simboliu (galima tik vienu), tai galima padaryti prirašę simbolį prie lygiavimo ženklo. Kiekviename stulpelyje pakeiskime tarpus kitais simboliais:

.py
# ...
# The same variables as in the earlier example

# Header row
print(f"{'Name':*<10} {'Position':Z>18} {'Age':+>8} {'Salary':?>8}")

# Data rows
print(f"{name_1:*<10} {position_1:Z>18} {age_1:+>8} {salary_1:?>8}")
print(f"{name_2:*<10} {position_2:Z>18} {age_2:+>8} {salary_2:?>8}")
print(f"{name_3:*<10} {position_3:Z>18} {age_3:+>8} {salary_3:?>8}")

# Outputs:
# Name****** AAAAAAAAAAPosition +++++Age ==Salary
# Alice***** ASoftware engineer ++++++19 ====1200
# Bob******* AAAAAAAAAAATeacher ++++++25 =====990
# Charlie*** AAAAAAData analyst ++++++26 ====2790

Prieš pabaigiant analizuoti šį skyrių, reiktų atkreipti dėmesį, kaip formatuojamas eilutės tipo reikšmės tiesiogiai f-string sintaksėje. Vietoje to, kad rašytume tekstą dvigubose kabutės, tekstą rašome viengubose.

Python kalboje viengubos ir dvigubos kabutės gali būti keičiamos tarpusavyje, nes funkcionalumas jų yra toks pats.

.py
# Single quotation marks
string1 = 'Hello, World!'

# Double quotation marks
string2 = "Hello, World!"

print(string1)  # Output: Hello, World!
print(string2)  # Output: Hello, World!


# -------------------------------------------------
# Using double quotes to include a single quote inside the string
string_with_single_quote = "It's a beautiful day!"

# Using single quotes to include double quotes inside the string
string_with_double_quote = 'She said, "Hello!"'

print(string_with_single_quote)  # Output: It's a beautiful day!
print(string_with_double_quote)  # Output: She said, "Hello!"


# ----------------------------------------------------
# Triple double quotes
multi_line_string1 = """This is a
multi-line string
using triple double quotes."""

# Triple single quotes
multi_line_string2 = '''This is a
multi-line string
using triple single quotes.'''

print(multi_line_string1)
print(multi_line_string2)

Eilutės reikšmių modifikavimas

Toliau pateiksime, kaip dar galima modifikuoti eilutės reikšmes. Čia pateiksime keletą lengvesnių, kitose pamokose, kai šiek tiek įgūsite, išmoksite sudėtingesnių metodų.

Apie Python kalboje esančius string metodus galite pasiskaityti w3schools.

DIDŽIOSIOS ir mažiosios raidės

Eilutės reikšmės visus simbolius pakeisti į didžiąsias raides arba į mažąsias galima su metodais lower() ir upper()

.py
my_string="I aM sTrInG"
uppercase_string=my_string.upper()
lowercase_string=my_string.lower()

print(f"{'Original string:':<20} {my_string}")
print(f"{'Uppercase string:':<20} {uppercase_string}")
print(f"{'Lowercase string:':<20} {lowercase_string}")

# Outputs:
# Original string:     I aM sTrInG
# Uppercase string:    I AM STRING
# Lowercase string:    i am string

Kitas pavyzdys:

.py
scream="aaaaaaaaaaaaaaaah!"

print("scream in lowercase:")
story = f'''Once upon a time, Ella wandered into the forest 
and suddenly screamed, "{scream}" when she saw a squirrel.
'''
print(story)

print("scream in uppercase:")
story = f'''Once upon a time, Ella wandered into the forest 
and suddenly screamed, "{scream.upper()}" when she saw a squirrel.'''
print(story)

# outputs:
# scream in lowercase:
# Once upon a time, Ella wandered into the forest 
# and suddenly screamed, "aaaaaaaaaaaaaaaah!" when she saw a squirrel.

# scream in uppercase:
# Once upon a time, Ella wandered into the forest 
# and suddenly screamed, "AAAAAAAAAAAAAAAAH!" when she saw a squirrel.

Šiuos metodus galima naudoti iš karto po kabučių:

.py
print("Hello".upper())
print("Hello".lower())

# outputs:
# HELLO
# hello

Pakeitimas (iš a į b)

Tarkime, reikia parašyti istoriją anglų kalba, bet darbą pasilikote paskutinei minutei. Skubant vietoje and parašėte adn. Jeigu šis tekstas, būtų rašomas „Microsoft Word“ programoje, jūs pasinaudotumėte find and replace funkcija (spartieji klavišai ctrlH, video medžiaga). Kitose teksto rengimo programose ši funkcija taip pat egzistuoja. Pavyzdžiui, „Visual Studio Code“, per kurią tikriausiai rašote kodą, taip pat veikia spartieji klavišai ctrlH (arba ctrlF ir paspaudus rodyklę). Nuoroda į šios funkcijos aprašymą - Find and replace text in Visual Studio.

Programavime irgi yra tokia funkcija - string kintamojo metodas replace(). Tai ištaisykime tekste klaidingai parašytus adn:

.py
# Generated with ChatGPT
text = """
Ella loved to explore the forest adn the hills. Every day, she would pack a sandwich adn a bottle of water, adn head out on her adventure. The birds would sing adn the leaves would rustle in the wind. She always hoped to find something new adn exciting.

One day, while walking, she found an old, abandoned cabin. The door was ajar adn the windows were broken. She peered inside adn saw a dusty old book on the table. The cover was ornate adn the pages were yellowed with age. She carefully opened the book adn began to read.

The book told stories of the forest adn the creatures that lived within. It spoke of hidden treasures adn ancient secrets. Ella was captivated adn spent hours reading. As the sun began to set, she realized it was time to go home. She carefully placed the book back on the table adn made her way back through the forest, thinking about all the new places she would explore tomorrow.

The next morning, Ella woke up early adn couldn't wait to return to the cabin. She quickly ate her breakfast adn packed her bag. On her way, she met her friend Jack. She told him about the cabin adn the book. Jack was excited adn decided to join her. Together, they walked through the forest adn found the cabin.

Inside, they found not only the book but also a map. The map showed a path to a hidden waterfall. Ella adn Jack decided to follow the map adn see where it led. The path was winding adn overgrown, but they were determined. After a long walk, they finally reached the waterfall. It was beautiful adn the water sparkled in the sunlight.

They spent the rest of the day exploring the area adn playing in the water. As the day came to an end, they knew they had found a special place. They made a pact to return often adn discover more of the forest's secrets together.
"""

print("------------------------------------------------------------------")
print("Original text:")
print("------------------------------------------------------------------")
print(text)

print("------------------------------------------------------------------")
print("Fixed text ('adn' replaced with 'and'):")
print("------------------------------------------------------------------")

print(text.replace("adn", "and"))

Tokio kodo išvestis:

text
------------------------------------------------------------------
Original text:
------------------------------------------------------------------

Ella loved to explore the forest adn the hills. Every day, she would pack a sandwich adn a bottle of water, adn head out on her adventure. The birds would sing adn the leaves would rustle in the wind. She always hoped to find something new adn exciting.

One day, while walking, she found an old, abandoned cabin. The door was ajar adn the windows were broken. She peered inside adn saw a dusty old book on the table. The cover was ornate adn the pages were yellowed with age. She carefully opened the book adn began to read.

The book told stories of the forest adn the creatures that lived within. It spoke of hidden treasures adn ancient secrets. Ella was captivated adn spent hours reading. As the sun began to set, she realized it was time to go home. She carefully placed the book back on the table adn made her way back through the forest, thinking about all the new places she would explore tomorrow.

The next morning, Ella woke up early adn couldn't wait to return to the cabin. She quickly ate her breakfast adn packed her bag. On her way, she met her friend Jack. She told him about the cabin adn the book. Jack was excited adn decided to join her. Together, they walked through the forest adn found the cabin.

Inside, they found not only the book but also a map. The map showed a path to a hidden waterfall. Ella adn Jack decided to follow the map adn see where it led. The path was winding adn overgrown, but they were determined. After a long walk, they finally reached the waterfall. It was beautiful adn the water sparkled in the sunlight.

They spent the rest of the day exploring the area adn playing in the water. As the day came to an end, they knew they had found a special place. They made a pact to return often adn discover more of the forest's secrets together.

------------------------------------------------------------------
Fixed text ('adn' replaced with 'and'):
------------------------------------------------------------------

Ella loved to explore the forest and the hills. Every day, she would pack a sandwich and a bottle of water, and head out on her adventure. The birds would sing and the leaves would rustle in the wind. She always hoped to find something new and exciting.

One day, while walking, she found an old, abandoned cabin. The door was ajar and the windows were broken. She peered inside and saw a dusty old book on the table. The cover was ornate and the pages were yellowed with age. She carefully opened the book and began to read.

The book told stories of the forest and the creatures that lived within. It spoke of hidden treasures and ancient secrets. Ella was captivated and spent hours reading. As the sun began to set, she realized it was time to go home. She carefully placed the book back on the table and made her way back through the forest, thinking about all the new places she would explore tomorrow.

The next morning, Ella woke up early and couldn't wait to return to the cabin. She quickly ate her breakfast and packed her bag. On her way, she met her friend Jack. She told him about the cabin and the book. Jack was excited and decided to join her. Together, they walked through the forest and found the cabin.

Inside, they found not only the book but also a map. The map showed a path to a hidden waterfall. Ella and Jack decided to follow the map and see where it led. The path was winding and overgrown, but they were determined. After a long walk, they finally reached the waterfall. It was beautiful and the water sparkled in the sunlight.

They spent the rest of the day exploring the area and playing in the water. As the day came to an end, they knew they had found a special place. They made a pact to return often and discover more of the forest's secrets together.

Tik reiktų įsiminti, kad su šis metodas yra jautrus mažosioms ir didžiosioms raidėms (angl. case-sensitive)

.py
# "pink"       -    -    -    -    -    -    -    -    -    -    -    +    -    -    -    -    -    -    -
words_salad = "PINK Pink pInk piNk pinK PInk pINk piNK PiNk PinK pINk pink piNK piNK PINk PiNK pINK PInK pINK"
# replace "pink" with "+I AM CHANGED+".
modified_salad = words_salad.replace("pink", "+I AM CHANGED+")
print(modified_salad)

# Outputs:     PINK Pink pInk piNk pinK PInk pINk piNK PiNk PinK pINk +I AM CHANGED+ piNK piNK PINk PiNK pINK PInK pINK

Taip pat metode replace() galima nurodyti, kiek surastų reikšmių pakeisti. Tą padaryti pateikę trečiąjį argumentą.

.py
six_potatoes = "potato potato potato potato potato potato"
# We will change occurences of three potatoes to tomato.
three_potatoes = six_potatoes.replace("potato", "tomato", 3)
print(three_potatoes) # prints: tomato tomato tomato potato potato potato

Metodas keičia ne tik visą sutiktą žodį, bet pakeičia surastą žodį, kito žodžio dalyje:

.py
similar_words="down, downtown, breakdown, downgrade, standdown, downbeat, throwdown"
print(similar_words.replace("down", "up")) 

# Outputs: up, uptown, breakup, upgrade, standup, upbeat, throwup

Galima pakeisti ir tarpo simbolį:

.py
text_with_spaces="I am going to learn programming"
print(text_with_spaces.replace(" ", "---"))

# Outputs: 
# I---am---going---to---learn---programming

Sudėtis

Nors ir nelabai intuityvu, bet eilutės tipo kintamuosius galima sudėti. Sudėties rezultas yra dvi sujungtos eilutės. Šiam dalykui parodyti, panaudokime tradicinį „Labas, Pasauli“:

.py
greeting="Hello"
subject="World"

message=greeting+subject
print(message) # prints: HelloWorld

Kadangi trūksta tarpo ir skyrybos, patobulinkime kodą:

.py
greeting="Hello"
subject="World"

message=greeting+ ", " + subject
print(message) # prints: Hello, World

Kadangi žinome f-strings sintaksę, sudėties operaciją galima lengvai pakeisti naujai išmoktu dalyku:

.py
greeting="Hello"
subject="World"

message=f"{greeting}, {subject}"
print(message) # prints: Hello, World

Kaip ir dažniausiai, programavime yra ne vienas būdas atlikti gauti rezultatą. Priklausomai nuo situacijos, vienas būdas gali būti geresnis už kitą.

Daugyba

Eilutės kintamąjį galima padauginti iš skaičiaus. Jeigu tekstą dauginsime iš skaičiaus , tai rezultate - naujasis tekstas bus pradinis tekstas pakartotas kartų:

.py
greeting="Hello"
print(greeting) # prints: Hello

greeting_10_times = greeting * 10
print(greeting_10_times) # prints: HelloHelloHelloHelloHelloHelloHelloHelloHelloHello

Su daugyba galima padaryti progreso juosta:

.py
# Define the progress values
current = 75
total = 100
bar_length = 50

# Calculate the progress
progress = current / total

# Create the bar
arrow = '#' * int(progress * bar_length)
spaces = '-' * (bar_length - len(arrow))

# Print the progress bar
print(f"[{arrow}{spaces}] {int(progress * 100)}%")

# Outputs:
# [#####################################-------------] 75%

Jeigu norite jundančios juostos, jums prireiks daugiau programavimo žinių, kurias įgausite vėliau, bet galite išbandyti kodą ir dabar:

.py
import time
import random

def progress_bar(current, total, bar_length=50):
    progress = current / total
    arrow = '#' * int(progress * bar_length)
    spaces = '-' * (bar_length - len(arrow))
    print(f"\n[{arrow}{spaces}] {int(progress * 100)}%", end='')

total = 100  # Total steps in the progress
current = 0

while current < total:
    progress_bar(current, total)
    time.sleep(0.2)  # Simulate work being done
    current += random.randint(1, 5)  # Randomly increment progress

# Ensure the progress bar completes at 100%
progress_bar(total, total)
print("\nProcess complete!")

Vėliau daugyba panaudosime patobulinant anksčiau sudarytą lentelę.

Naujos eilutės simbolis

Visi tekstas yra sudarytas simbolius. Taip pat savo simbolį turi ir ta vieta, kuria atsiranda paspaudus ENTER klavišą. Nauja eilutė yra (dažniausiai) koduojama simboliu \n. Paleidus žemiau patiktą kodą, pamatysite, kad, skirtingai nei įprastai, tekstas išskaidytas į dvi dalis:

.py
message="hello,\nWorld!"
print(message)

# Outputs:
# hello,
# World!

Ateityje prireiks išsivalyti string kintamuosiuos nuo naujos eilutės simbolio \n. Tą galima padaryti su replace() metodu:

.py
message="hello,\nWorld!"
message=message.replace("\n", " ")
print(message)

# Outputs:
# hello,
# World!

Escape simbolis

Ką daryti jeigu norime atvaizduoti tekstą su „\n“ simboliu: pavyzdžiui „Norint padaryti naują eilutę, programuojant reikia rašyti simbolį \n“. Jeigu bandysime tai atspausdinti, tai nebus atvaizduotas simbolis „\n“, gale atsiras nauja eilutė:

.py
print("Norint padaryti naują eilutę, programuojant reikia rašyti simbolį \n")

# Outputs:
# Norint padaryti naują eilutę, programuojant reikia rašyti simbolį 
#

Tam programavime yra naudojami escape simbolis (angl. character, nėra lietuviško atitikmens). Tam naudojamas pasvirasis brūkšnys „/“, o jis turi būti prirašytas prie simobolio, kuris įprastai turi kitą prasmę. Norint parašyti tekste „\n“, reikia kode reikia tai pateikti, kaip \\n:

.py
print("Norint padaryti naują eilutę, programuojant reikia rašyti simbolį \\n")

# Outputs:
# Norint padaryti naują eilutę, programuojant reikia rašyti simbolį \n

Yra ir kitų simbolių, kurie turi kitą prasmę tekste, o norint atvaizduoti reikia prirašyti pasvirąjį brūkšnį:

Pats pasvirasis brūkšnys \ yra specialus simbolis, kurį atvaizduoti tiesiog parašius neišeis. Kodas žemiau išauks klaidą:

.py
print("Slash \")

Šitas kodas leis parašyti pasvirąjį brūkšnį:

.py
print("Slash \\")

Blogas kodas - kabučių rašymas tekste:

.py
print("Quotation mark "")

Kabutės su escape simboliu:

.py
print("Quotation mark \"")

Užduotis - lentelės patobulinimas

Panaudokime anksčiau aprašytus būdus teksto modifikavimui ir patobulinkime lentelę.

Pridėkite daugiau duomenų ir toliau šių kodo eilučių nemodifikuokite:

.py
name_1 = "Alice"
position_1 = "Software engineer"
age_1 = 19
salary_1 = 1200
annual_bonus_1 = salary_1 * 0.1  # 10% of salary

name_2 = "Bob"
position_2 = "Teacher"
age_2 = 25
salary_2 = 990
annual_bonus_2 = salary_2 * 0.15  # 15% of salary

name_3 = "Charlie"
position_3 = "Data analyst"
age_3 = 26
salary_3 = 2790
annual_bonus_3 = salary_3 * 0.2  # 20% of salary

name_4 = "David"
position_4 = "Research Scientist"
age_4 = 30
salary_4 = 15000.75
annual_bonus_4 = salary_4 * 0.25  # 25% of salary

name_5 = "Eve"
position_5 = "Graphic Designer"
age_5 = 28
salary_5 = 3500
annual_bonus_5 = salary_5 * 0.12  # 12% of salary

Pasinaudokite teksto modifikavimo galimybėmis ir sukurkite tokią lentelę (ar labai panašią į ją):

text
=====================================================================
| Name       | Position           | Age |     Salary | Annual Bonus |
=====================================================================
| Alice      | Software engineer  |  19 |    1200.00 |       120.00 |
---------------------------------------------------------------------
| Bob        | Teacher            |  25 |     990.00 |       148.50 |
---------------------------------------------------------------------
| Charlie    | Data analyst       |  26 |    2790.00 |       558.00 |
---------------------------------------------------------------------
| David      | Research Scientist |  30 |   15000.75 |      3750.19 |
---------------------------------------------------------------------
| Eve        | Graphic Designer   |  28 |    3500.00 |       420.00 |
=====================================================================

Būtina įvertinti, kad duomenys gali keistis, todėl reikia vengti konstantų kuriant lentelių linijas. Pavyzdžiui, antraštinį stulpelį galite patalpinti į kintamąjį ir sudaryti linijas pagal jos ilgį:

.py
header = f"{'Name':<10} {'Position':>18} {'Age':>8} {'Salary':>8}"
print('=' * len(header))
print(header)
print('=' * len(header))

Venkite programuojant daryti šitaip:

.py
header = f"{'Name':<10} {'Position':>18} {'Age':>8} {'Salary':>8}"
print('=' * 47)
print(header)
print('=' * 47)

Pilnai sudaryti lentelę jums reikės:

  • Pridėti naujus du stulpelius;
  • Sulygiuoti du pirmus stulpelius pagal kairį kraštą, likusius pagal dešinįjį;
  • Stulpelių „Salary“ ir „Annual Bonus“ reikšmes nurodyti dviejų skaitmenų po kablelio tikslumu;
  • Antraštinę eilutę eilutę atskirti su linija sudaryta iš „=“;
  • Pirmąją ir paskutiniąją kraštines padaryti linija iš „=“;
  • Sudėti vertikalias lentelės kraštines - brūkšnelius „|“;
  • Galite paekspermentuoti ir pamodifikuoti lentelę pagal savo vaizduotę;

Skaitalai

Toliau keleta pateikta keleta temų, apie kurias galite pasiskaityti, jeigu jus ypatingai domina programavimas.

Kiti formatavimo būdai

Anksčiau aprašytas formatavimo būdas su f-string Python kalboje atsirando visai neseniai, 2015 metais, o pati kalba gyvuoja nuo 1991 m. Toliau bus trumpai aprašyti kiti galima būdai, kuriuos galite savarankiškai pasiskaityti savarankiškai rastuose šaltiniuose.

Sudėtis

Paprastai atvejais galima naudoti sudėties operatorių:

.py
name = "Alice"
age = 19
formatted_string = "Name: " + name + ", Age: " + str(age)
print(formatted_string) # prints: Name: Alice, Age: 19

Procento operatorius

Prieš f-strings, Python kalboje buvo naudojamas procento % operatorius:

.py
name = "Alice"
age = 19
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string) # prints: Name: Alice, Age: 19

format() metodas

Sintaksė, panaudojimo būdas panašus į f-string:

.py
name = "Alice"
age = 19
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string) # prints: Name: Alice, Age: 19

# With positional arguments
formatted_string = "Name: {0}, Age: {1}".format(name, age)
print(formatted_string) # prints: Name: Alice, Age: 19

# With named arguments
formatted_string = "Name: {name}, Age: {age}".format(name=name, age=age)
print(formatted_string) # prints: Name: Alice, Age: 19

Šis metodas naudingas tada, kad galima iš anksto aprašyti šabloną, pagal kurį sudarysime formatuotą tekstą. Tai labiau naudinga didesnėms, sudėtingesnėms programoms. Pavyzdyje panaudota žodyno duomenų struktūra, apie kurią sužinosite vėliau:

.py
# Create the template
template = "Name: {name}, Age: {age}, Position: {position}"

# Use the template later to format with actual values
data_1 = {"name": "Alice", "age": 19, "position": "Software Engineer"}
data_2 = {"name": "Bob", "age": 25, "position": "Teacher"}
data_3 = {"name": "Charlie", "age": 26, "position": "Data Analyst"}

# Format using the template and the data dictionaries
formatted_string_1 = template.format(name=data_1['name'], age=data_1['age'], position=data_1['position'])
formatted_string_2 = template.format(name=data_2['name'], age=data_2['age'], position=data_2['position'])
formatted_string_3 = template.format(name=data_3['name'], age=data_3['age'], position=data_3['position'])

print(formatted_string_1) # prints: Name: Alice, Age: 19, Position: Software Engineer
print(formatted_string_2) # prints: Name: Bob, Age: 25, Position: Teacher
print(formatted_string_3) # prints: Name: Charlie, Age: 26, Position: Data Analyst

RegEx

RegEx (arba Regex) įrankiui paaiškinti ir išmokti reiktų atskiros, ilgos serijos pamokų. Pats žodis yra dviejų žodžių trumpinys - regular expression (lietuviškai reguliarioji išraiška). Šis įrankis nėra išskirtinis Python kalbai, visose moderniose programavimo kalbose šį galima sutikti. Taip pat jį galima panaudoti ir Visual Studio Code įrankyje, paaieškos įrankyje (užeikite su pele ant simbolio su žvaigždute):

Šis įrankis atsiras ir „Microsoft Excel“ programoje (šaltinis).

RegEx įrankis naudojamas tose vietose, kur reikia paieškos tekste, teksto manipuliacijos.

Prieš skaitant pavyzdys, būtina susipažinti su paprastesniais pavyzdžiais iš tinklapio W3Schools.

Pirmas pavyzdys

Tarkime tokią situaciją, kad įmonėje procesai yra mažai skaitmenizuoti. Įmonės tinklalapyje asmuo turi prisiregistruoti su paštu, kurio forma yra vardas.pavarde@pastas.com. El. pašto adresas gali būti praplėstas su + ženklu ir gali atrodyti šitaip: vardas.pavarde+10@pastas.com ar vardas.pavarde+spam@pastas.com (tokius adresus leidžia sudaryti gmail el. paštas). Jums vadovas nurodė jam sudaryti asmenų sąrašą ištrynus el.pašto adreso domeną (ženklą @ ir toliau esančią pašto dalį). Kadangi mokote programuoti, tai jūs sukūrėte trumpą Python kodą, kuris visą šį darbą atlieka per momentą (pavyzdžiui, paimta tik 10 el. pašto adresų)(kadangi kodas sudėtingas, nesistenkite jo suprasti, žiūrėkite į tekstus „prieš“ ir „po“):

.py
import re

# Example list of email addresses
emails = [
    "john.doe@example.com",
    "jane.smith+123@anotherdomain.com",
    "alice.jones+extra@sample.org",
    "bob.brown+sales@domain.net",
    "carol.white@company.co",
    "david.black+2023@service.io",
    "eva.green+work@domain.org",
    "frank.red@workplace.com",
    "grace.blue+notes@otherdomain.com",
    "harry.yellow+personal@mail.org"
]

# Before parsing
print("Before parsing:")
for email in emails:
    print(email)

def parse_names(emails):
    name_pattern = re.compile(r'([a-z]+)\.([a-z]+)(\+[a-z0-9]+)?@[a-z]+\.[a-z]+', re.IGNORECASE)
    parsed_names = []

    for email in emails:
        match = name_pattern.match(email)
        if match:
            name, surname, _ = match.groups()
            parsed_names.append((name.capitalize(), surname.capitalize()))

    return parsed_names

# Parsing names from the emails
parsed_names = parse_names(emails)

# After parsing
print("\nAfter parsing:")
for name, surname in parsed_names:
    print(f"Name: {name}, Surname: {surname}")

Programos išvestis

text
Before parsing:
john.doe@example.com
jane.smith+123@anotherdomain.com
alice.jones+extra@sample.org
bob.brown+sales@domain.net
carol.white@company.co
david.black+2023@service.io
eva.green+work@domain.org
frank.red@workplace.com
grace.blue+notes@otherdomain.com
harry.yellow+personal@mail.org

After parsing:
Name: John, Surname: Doe
Name: Jane, Surname: Smith
Name: Alice, Surname: Jones
Name: Bob, Surname: Brown
Name: Carol, Surname: White
Name: David, Surname: Black
Name: Eva, Surname: Green
Name: Frank, Surname: Red
Name: Grace, Surname: Blue
Name: Harry, Surname: Yellow

Antras pavyzdys

Kita situacija - esate tyrėjas tiriantis skaitmeninę komunikaciją socialiniuose tinkluose. Jums svarbu suprasti kokius žodžius žmonės vartoja dažniausiai skaitmeninėje erdvėje. Tarkime turime vieną socialinį įrašą (realiu atveju, turėtume milžinišką kiekį įrašų):

text
Just had an AMAZING weekend getaway in the mountains!!! 🏔️ The weather was perfect, and the views were ABSOLUTELY breathtaking. 🌄
Hiking trails were challenging but so WORTH it. 🚶‍♂️ Spent the evenings by the campfire with friends, sharing stories and enjoying
some delicious homemade food. 🍲 Can't wait to go back!!! If you love nature and adventure, I highly recommend visiting this place. 🌲
Also, saw some wildlife including deer and a bear from a safe distance!!! 🦌🐻 Hiking is such a rewarding activity, and being in nature 
is incredibly refreshing. 🌳 The sounds of the forest, the fresh air, and the beautiful scenery make it all worthwhile. 🌿
Whether it's a short walk or a long trek, hiking is always an adventure. 🌄 Every trip brings new experiences and memories to cherish. 
Can't get enough of this amazing place and its stunning trails. 🥾🏞️ Truly a hiker's paradise. If you haven't been here, you're missing out!
The wildlife here is so diverse, and the landscapes are just stunning. 🌺🍃 Hiking enthusiasts, this place is a must-visit! 🏕️✨
#weekend #nature #hiking #adventure #friends #relax #wildlife #explore #outdoors @naturelover @hikingworld

Suskaičiuokime panaudotų žodžių dažnumą:

.py
import re

# Messy example post with emojis
post = """
Just had an AMAZING weekend getaway in the mountains!!! 🏔️ The weather was perfect, and the views were ABSOLUTELY breathtaking. 🌄
Hiking trails were challenging but so WORTH it. 🚶‍♂️ Spent the evenings by the campfire with friends, sharing stories and enjoying
some delicious homemade food. 🍲 Can't wait to go back!!! If you love nature and adventure, I highly recommend visiting this place. 🌲
Also, saw some wildlife including deer and a bear from a safe distance!!! 🦌🐻 Hiking is such a rewarding activity, and being in nature 
is incredibly refreshing. 🌳 The sounds of the forest, the fresh air, and the beautiful scenery make it all worthwhile. 🌿
Whether it's a short walk or a long trek, hiking is always an adventure. 🌄 Every trip brings new experiences and memories to cherish. 
Can't get enough of this amazing place and its stunning trails. 🥾🏞️ Truly a hiker's paradise. If you haven't been here, you're missing out!
The wildlife here is so diverse, and the landscapes are just stunning. 🌺🍃 Hiking enthusiasts, this place is a must-visit! 🏕️✨
#weekend #nature #hiking #adventure #friends #relax #wildlife #explore #outdoors @naturelover @hikingworld
"""

# Clean the text
# Remove hashtags, mentions, and special characters
cleaned_post = re.sub(r'[@#]\w+', '', post)
# Remove emojis and other non-alphanumeric characters
cleaned_post = re.sub(r'[^\w\s]', '', cleaned_post)
# Convert to lowercase
cleaned_post = cleaned_post.lower()

# Calculate word frequencies
words = cleaned_post.split()
stop_words = ['the', 'and', 'a', 'it', 'was', 'in', 'of', 'to', 'for', 'on', 'at', 'is', 'that', 'with', 'this', 'we', 'our', 'as', 'but', 'i', 'an']
word_counts = {}
for word in words:
    if word not in stop_words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1

# Display the results
print("Word Frequencies:")
for word, freq in sorted(word_counts.items(), key=lambda item: item[1], reverse=True):
    if(freq > 1):
        print(f"{word}: {freq}")

Šio kodo išvestis:

text
Word Frequencies:
hiking: 4
place: 3
just: 2
amazing: 2
were: 2
trails: 2
so: 2
some: 2
cant: 2
if: 2
you: 2
nature: 2
adventure: 2
wildlife: 2
its: 2
stunning: 2
here: 2

Toliau keletą kodo vietų detaliau. Pirmiausiai kodas importujojame biblioteką, kuri leidžia naudotis RegEx. Aprašomas duomenų kintamasis, kuriame yra tekstas apie įrašą. Tada pradedame duomenų valymą.

Naudojantis RegEx ištrinami visi žodžiai, kurie prasideda su simboliais „@“ „#“:

.py
cleaned_post = re.sub(r'[@#]\w+', '', post)

Tai aprašoma su '[@#]\w+' išraiška:

  • @#: Ši išraiškos dalis ieško simbolių esančių skliausteliuose. Ieškoma arba, @ arba #;
  • \w: Šis užrašas nurodo ieškoti betkurių žodžio simbolių. Žodžio simbolis yra raidės (mažosios ir didžiosios), skaičiai, apatinis brūkšnys (_);
  • +: Šis simbolis nurodo ieškoti vieno ar daugiau simbolių, kuris nurodytas prieš šį simbolį. Tai, \w+ ieškos vieno ar daugiau žodžio simbolio iš eilės.

Tai sujungus visa tai į išraišką, nurodoam ieškoti simbolių sekų, kurie prasideda su @ arba #, po kurių seka viena ar daugiau simbolių. Tai šiuo atveju žodžiai: „#weekend“, „#nature“, „#hiking“, „#adventure“, „#friends“, „#relax“, „#wildlife“, „#explore“, „#outdoors“, „@naturelover“, „@hikingworld“, yra pakeičiami tuščios eilutės reikšme ('') arba, kitaip tariant, ištrinami. Tai padaroma su re.sub() metodu. Po šio išvalymo tekstas atrodo taip:

text
Just had an AMAZING weekend getaway in the mountains!!! 🏔️ The weather was perfect, and the views were ABSOLUTELY breathtaking. 🌄
Hiking trails were challenging but so WORTH it. 🚶‍♂️ Spent the evenings by the campfire with friends, sharing stories and enjoying
some delicious homemade food. 🍲 Can't wait to go back!!! If you love nature and adventure, I highly recommend visiting this place. 🌲
Also, saw some wildlife including deer and a bear from a safe distance!!! 🦌🐻 Hiking is such a rewarding activity, and being in nature 
is incredibly refreshing. 🌳 The sounds of the forest, the fresh air, and the beautiful scenery make it all worthwhile. 🌿
Whether it's a short walk or a long trek, hiking is always an adventure. 🌄 Every trip brings new experiences and memories to cherish. 
Can't get enough of this amazing place and its stunning trails. 🥾🏞️ Truly a hiker's paradise. If you haven't been here, you're missing out!
The wildlife here is so diverse, and the landscapes are just stunning. 🌺🍃 Hiking enthusiasts, this place is a must-visit! 🏕️✨

Toliau su vėl su RegEx, ieškomi visui ne žodžių simboliai (šauktukai, kableliai, emociukai) ir vėl pakeičiami niekuo:

.py
cleaned_post = re.sub(r'[^\w\s]', '', cleaned_post)

Po šio išvalymo tekstas atrodo taip:

text
Just had an AMAZING weekend getaway in the mountains  The weather was perfect and the views were ABSOLUTELY breathtaking 
Hiking trails were challenging but so WORTH it  Spent the evenings by the campfire with friends sharing stories and enjoying
some delicious homemade food  Cant wait to go back If you love nature and adventure I highly recommend visiting this place 
Also saw some wildlife including deer and a bear from a safe distance  Hiking is such a rewarding activity and being in nature 
is incredibly refreshing  The sounds of the forest the fresh air and the beautiful scenery make it all worthwhile 
Whether its a short walk or a long trek hiking is always an adventure  Every trip brings new experiences and memories to cherish 
Cant get enough of this amazing place and its stunning trails  Truly a hikers paradise If you havent been here youre missing out
The wildlife here is so diverse and the landscapes are just stunning  Hiking enthusiasts this place is a mustvisit

Toliau su dviem eilutės

.py
# Convert to lowercase
cleaned_post = cleaned_post.lower()

# Calculate word frequencies
words = cleaned_post.split()

visas tekstas padaromas mažosiomis raidėmis ir išskaidomas į pavienius žodžius - taip padaromas žodžių sąrašas:

.py
['just', 'had', 'an', 'amazing', 'weekend', 'getaway', 'in', 'the', 'mountains', 'the', 'weather', 'was', 'perfect', 'and', 'the', 'views', 'were', 'absolutely', 'breathtaking', 'hiking', 'trails', 'were', 'challenging', 'but', 'so', 'worth', 'it', 'spent', 'the', 'evenings', 'by', 'the', 'campfire', 'with', 'friends', 'sharing', 'stories', 'and', 'enjoying', 'some', 'delicious', 'homemade', 'food', 'cant', 'wait', 'to', 'go', 'back', 'if', 'you', 'love', 'nature', 'and', 'adventure', 'i', 'highly', 'recommend', 'visiting', 'this', 'place', 'also', 'saw', 'some', 'wildlife', 'including', 'deer', 'and', 'a', 'bear', 'from', 'a', 'safe', 'distance', 'hiking', 'is', 'such', 'a', 'rewarding', 'activity', 'and', 'being', 'in', 'nature', 'is', 'incredibly', 'refreshing', 'the', 'sounds', 'of', 'the', 'forest', 'the', 'fresh', 'air', 'and', 'the', 'beautiful', 'scenery', 'make', 'it', 'all', 'worthwhile', 'whether', 'its', 'a', 'short', 'walk', 'or', 'a', 'long', 'trek', 'hiking', 'is', 'always', 'an', 'adventure', 'every', 'trip', 'brings', 'new', 'experiences', 'and', 'memories', 'to', 'cherish', 'cant', 'get', 'enough', 'of', 'this', 'amazing', 'place', 'and', 'its', 'stunning', 'trails', 'truly', 'a', 'hikers', 'paradise', 'if', 'you', 'havent', 'been', 'here', 'youre', 'missing', 'out', 'the', 'wildlife', 'here', 'is', 'so', 'diverse', 'and', 'the', 'landscapes', 'are', 'just', 'stunning', 'hiking', 'enthusiasts', 'this', 'place', 'is', 'a', 'mustvisit']

O tada suskaičiuojamas šių žodžių dažnumas (panaudojama žodyno duomenų struktūra) ir atspausdinami žodžiai, kurie kartojasi daugiau nei kartą. Skaičiuojant žodžių dažnumą nėra įtraukiami specifiniai trumpi žodžiai, kurie aprašomi stop_words sąraše:

.py
stop_words = ['the', 'and', 'a', 'it', 'was', 'in', 'of', 'to', 'for', 'on', 'at', 'is', 'that', 'with', 'this', 'we', 'our', 'as', 'but', 'i', 'an']
word_counts = {}
for word in words:
    if word not in stop_words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1

# Display the results
print("Word Frequencies:")
for word, freq in sorted(word_counts.items(), key=lambda item: item[1], reverse=True):
    if(freq > 1):
        print(f"{word}: {freq}")

O toliau šią gautą informaciją iš socialinio tinklo įrašo galima panaudoti nustant įrašo temą, emociją, tai priklauso nuo užduoties, kurią vykdo analitikas. Galima panaudoti apmokinant dirbtinio intelekto modelį. Pavyzdžiui, turinti šį žodžių pasikartojimo dažnumą, galima spręsti, kad žmogus rašė apie žygį (žodžiai „hiking“, „trails“, „nature“, „adventure“), kad tai rašė su pakylėta emocija (žodžiai „amazing“, „stunning“). Socialiniai tinklai tokią informaciją gali išnaudoti parenkant jums reklamą.

Įsirašius bibliotekas wordcloud ir matplotlib, įrašius dvi komandas į konsolę:

pip3 install wordcloud

ir

pip3 install matplotlib

importavus kodo pradžioje dvi eilutes:

.py
from wordcloud import WordCloud
import matplotlib.pyplot as plt

ir pridėjus keletą eilučių kodo pabaigoje:

.py
# Generate word cloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate_from_frequencies(word_counts)

# Display the word cloud
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()

galima gauti neblogą vizualizaciją:

Baigiamieji žodžiai

RegEx galingas ir kompleksiškas įrankis. Viskas, kas parašyta šitam skyriuje, reikalauja ilgo mokymosi ir treniravimosi. Svarbu susipažinti su reguliaromis išraiškomis, žinoti jų galimybes. Jeigu tik pradėjote mokytis programuoti, tai nėra būtina žinoti, nes tai pažengusiųjų programuotojų tema. Jeigu įdomu, daugiau informacijos ieškokite savarankiškai.

Sukurta
su meile

Kontaktai

2024 — Vilius P.