0

Как сделать чтобы при вводе текста выводились только те слова в которых есть 1 цифра. Проблема в том, что программа выводит только 1 слово с строки в которой есть цифра.

from tkinter import *

def clear():
    input_entry.delete(0, END)
    output_entry.delete(0, END)

def display():

    s1 = input_entry.get()
    s2 = ''

    for word in s1.split():
        for char in word:
            if char.isdigit():
                s2 = word

    s_list = s2.split()

    s3 = ' '.join(s_list)

    output_entry.delete(0, END)

    output_entry.insert(0, s3)

root = Tk()

root.title("Тitle")

input_label = Label(text="Введите текст:")
output_label = Label(text="Результат:")

input_label.grid(row=0, column=0, sticky="w")
output_label.grid(row=1, column=0, sticky="w")

input_entry = Entry(width = 50)
output_entry = Entry(width = 50)

input_entry.grid(row=0,column=1, padx=5, pady=5)
output_entry.grid(row=1,column=1, padx=5, pady=5)

input_entry.insert(0, "Ввести текст")
output_entry.insert(0, "Результат")

display_button = Button(text="Старт", command=display)
clear_button = Button(text="Очистка", command=clear)

display_button.grid(row=2, column=0, padx=20, pady=5,
sticky="w")
clear_button.grid(row=2, column=1, padx=20, pady=5,
sticky="e")

root.mainloop()

2 ответа 2

1

У вас неверно реализована логика в методе display. Замените код на этот и всё будет работать.

def display():
    input_ = input_entry.get()
    correct_words = []
    for word in input_.split():
        count_digits = len([x for x in word if x.isdigit()])
        if count_digits == 1:
            correct_words.append(word)

    output_entry.delete(0, END)

    output_entry.insert(0, ' '.join(correct_words))
1
0

замените ваши вложенные циклы на это:

from re import findall

f = lambda x: len(findall('\d',x))==1
s3 = ' '.join(filter(f, s1.split()))

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.