حالت آفلاین — محتوا از حافظهٔ کش نمایش داده می‌شود
همهٔ تمرین‌ها

جستجوی واژه در خطوط فایل

تمرین آسان 92 visibility link download flag

برنامه‌ای بنویسید که تابعی داشته باشد و مسیر یک فایل و واژه‌ای را به‌عنوان ورودی بگیرد، سپس همهٔ خط‌هایی را که آن واژه را دارند چاپ کند. جست‌وجو به بزرگی و کوچکی حروف حساس باشد.

برای نمونه، اگر محتوای فایل products.txt چنین باشد:

Python book HTML book Wireless mouse

و واژهٔ جست‌وجو book باشد، خروجی مورد انتظار چنین است:

Python book HTML book Wireless mouse
👨‍💻 10 ساعت قبل کاربر ناشناس این تمرین رو مشاهده کرد

پاسخ‌ها 3

def print_matching_lines(file_path, word):
    with open(file_path, encoding="utf-8") as file:
        for line in file:
            if word in line:
                print(line, end="")

file_path = input()
word = input()
print_matching_lines(file_path, word)
پاسخ هوش مصنوعی Ai Python
def search_word(filename,word):
    with open(filename,"r") as f:
        for line in f:
            if word == line.strip():
                return word

    return "your word not found"
while True:
    file_name=input("enter your text file")
    my_word=input("enter your word for search in your text file")
    result=search_word(file_name,my_word)
    print(result)
    answer=input("if finish enter q elsse p")
    if answer=="q":
        break
    elif answer=="p":
        continue
from pathlib import Path

def search_word(file_path, word):
    content = Path(file_path).read_text(encoding="utf-8")

    for line in content.splitlines():
        if word in line:
            print(line)


Path("products.txt").write_text(
    "Python book HTML book Wireless mouse",
    encoding="utf-8"
)

search_word("products.txt", "book")

ارسال جواب

جوابت را با Markdown بنویس و ثبت کن

×
بستن