from tkinter import Tk, Text, END, INSERT, Label, CURRENT
class Application(Tk):
def __init__(self):
super().__init__()
self.widget_text = Text(self)
self.widget_text.pack(expand=True)
self.configure_key_words()
self.widget_text.bind("<KeyPress>", self.handler)
def get_last_line(self):
full_text = self.widget_text.get("1.0", END)
list_string = full_text.split('\n')[::-1]
last_line = list_string[1]
return last_line
def get_last_word(self):
last_word = self.get_last_line().split(' ')[-1]
return last_word
def configure_key_words(self):
self.widget_text.tag_config('apple', foreground='red', underline=1,
font=("Arial", 12, 'bold'))
self.widget_text.tag_config('banana', foreground='green',
font=("Arial", 12, 'bold'))
def handler(self, event):
last_word = self.get_last_word()
if event.char == ' ' or '\n':
line, _ = self.widget_text.index(CURRENT).split(".")
word_start_position = self.get_last_line().rfind(last_word)
match last_word:
case "яблоко":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'яблоко', 'apple')
case "банан":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'банан', 'banana')
def main():
Application().mainloop()
if __name__ == '__main__':
main()
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.8.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: list_data = ["Владимир Иванович Романчук",
...: ...: "Романчук Владимир Иванович",
...: ...: "Романчук Владимир Иванович Владимир Иванович",
...: ...: "Владимир Демидович Романчук",
...: ...: "Владимир Демидович Васильевич"]
In [2]: search_line = "Романчук Владимир Иванович"
In [3]: results = set([string for string in list_data for word in search_line if word in string])
In [4]: print(results)
{'Владимир Демидович Васильевич', 'Романчук Владимир Иванович', 'Владимир Иванович Романчук', 'Владимир Демидович Романчук', 'Романчук Владимир Иванович Владимир Иванович'}
In [5]:
from io import StringIO
text_file = StringIO()
text_file.write("История 1")
text_file.write("\r\n")
text_file.write("История 2")
text_file.write("\r\n")
text_file.write("История 3")
text_file.write("\r\n")
text_file.seek(0)
# print(repr(text_file.read()))
def all_stories():
return [storie for storie in text_file.readlines() if "\r\n"]
def get_storie(index):
return all_stories()[index]
print(get_storie(0))
a,b,c,d = 4, 4, 2, 4
if a - 1:
print("True")
if a + 1:
print("True")
if a - 1 == c:
print("True")
else:
print("False")
if a + 1 == c:
print("True")
else:
print("False")
print(True and True)
print(False and False)
print(True and False)
print(True and True or False and False)
class SimpleDataBase(dict):
def __init__(self):
super().__init__({"World": "Мир"})
def __str__(self):
data = "".join(f"{key}: {value}\n" for key, value in self.items())
return f"{data}"
def update_db(self, key, value):
self.update({key: value})
def main():
simple_data_base = SimpleDataBase()
print(simple_data_base) # World: Мир
simple_data_base.update_db("Red", "Красный")
print(simple_data_base) # World: Мир
# Red: Красный
if __name__ == '__main__':
main()
zip
aa = [1,2,3]
bb=['a','b','c']
for a, b in zip(aa, bb):
print(str(a)+"swap"+b)
import requests
url = "https://drive.google.com/uc?id=1UCKuSaZ6zDg-NA9LxLspErVw0y2Qjh3Y"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"}
def main():
client = requests.Session()
response = client.get(url, headers=headers)
print(response.status_code)
FILE_TYPE = response.headers["content-type"].split("/")[1]
print(FILE_TYPE)
with open(f"video_file.{FILE_TYPE}", "wb") as video_file:
video_file.write(response.content)
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
class StopComputerWorking(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("background: black;")
self.setWindowOpacity(0.8)
self.showFullScreen()
layout = QVBoxLayout()
layout.setAlignment(Qt.AlignHCenter | Qt.AlignCenter)
self.setLayout(layout)
label = QLabel()
label.setStyleSheet("color: red;")
label.setText("По ходу вы подхватили вирус)")
label.setAlignment(Qt.AlignCenter)
label.setFont(QFont("Arial", 40))
layout.addWidget(label)
def keyReleaseEvent(self, event):
# Закрытие на кнопку Escape
if event.key() == Qt.Key_Escape:
self.close()
super().keyReleaseEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = StopComputerWorking()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QSizePolicy, QGridLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from PIL import Image
from PIL import ImageQt
class DrawOnPython(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Пример рисования в Python")
self.setGeometry(300, 300, 400, 300)
self.label_image = QLabel()
self.label_image.setScaledContents(True)
self.label_image.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.label_image.setAlignment(Qt.AlignCenter)
self.layout = QGridLayout(self)
self.layout.addWidget(self.label_image, 0, 0)
self.create_image()
self.show_image()
def create_image(self):
image = Image.new(mode="RGB", size=(20, 20))
self.image = image.convert("RGBA")
self.image.putpixel((3, 4), (255, 0, 0))
def show_image(self):
image_qt = ImageQt.ImageQt(self.image)
pixmap = QPixmap.fromImage(image_qt)
self.label_image.setPixmap(pixmap)
def main():
qapp = QApplication([])
draw_on_python = DrawOnPython()
draw_on_python.show()
sys.exit(qapp.exec())
if __name__ == '__main__':
main()
import random
class List(list):
def __init__(self, values=[]):
super().__init__(values)
def shuffle(self):
random.shuffle(self)
def main():
array = List([i for i in range(20)])
print(f"Массив как есть: {array}")
array.shuffle() # перетасовываем
print(f"Перемешанный массив {array}")
if __name__ == '__main__':
main()
auth = threading.Thread(target=start_mon(start_auth_solo))
auth = threading.Thread(target=start_mon, args=(start_auth_solo,))
from time import sleep
from threading import Thread
def a(duration):
while True:
print('Я функция а')
sleep(duration)
def b(duration):
while 1:
print('Я функция b')
sleep(duration)
def c(duration):
while 1:
print('Я функция c')
sleep(duration)
def main():
ta = Thread(target=a, args=(1, ))
ta.start()
tb = Thread(target=b, args=(2, ))
tb.start()
tc = Thread(target=c, args=(3, ))
tc.start()
while True:
print('Я главный поток!')
sleep(5)
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Пример")
self.grid_layout = QGridLayout()
self.setLayout(self.grid_layout)
self.textEdit = QTextEdit(self)
self.textEdit.toPlainText()
self.pushButton = QPushButton('ok', self)
self.pushButton.move(50, 50)
self.pushButton.clicked.connect(self.pushButtonClickedHandler)
self.grid_layout.addWidget(self.textEdit, 0, 0)
self.grid_layout.addWidget(self.pushButton)
def pushButtonClickedHandler(self):
text = self.textEdit.toPlainText()
self.grid_layout.addWidget(QLabel(text = text))
if __name__ == '__main__':
app = QApplication(sys.argv)
form = Example()
form.show()
app.exec()