簡體   English   中英

選擇一個文件,然后詢問用戶他們正在python文件中尋找什么短語或單詞

[英]Choosing a file then asking user what phrase or word they are looking for in file in python

我正在嘗試制作一個簡單的python程序,使其在向用戶詢問單詞或短語的地方,然后詢問用戶要查找的文件或文件夾或文檔,然后說出該單詞或短語出現了多少次以及出現在哪里。 。

這是我的代碼,但似乎停止對我的工作,我不知道為什么,也不太了解python。 有人可以幫我解決這個問題,並幫助我制作上面解釋的程序嗎?

phrase_to_look_for = input("What phrase would you like to look for?")
file_to_search = file.open("my_file.txt")
contents_of_file = file_to_search.read()
if phrase_look_for in contents_of_file:
    print("The word is in the file.")
else:
    print("The phrase is not in the file.")

謝謝

在bash中運行文件會引發多個錯誤。 以下代碼成功執行,我認為符合您的意圖

phrase_to_look_for = raw_input("What phrase would you like to look for?")
name_of_file = raw_input("What is the name of your file?") #File must be in the same folder
file_to_search = open(name_of_file,'r')
contents_of_file = file_to_search.read()
if phrase_to_look_for in contents_of_file:
    print("The word is in the file.")
else:
    print("The phrase is not in the file.")

您的崩潰(最初)的原因是您需要執行raw_input才能獲得正確的輸入。 這導致文件沒有打開屬性文件的錯誤。 在這種情況下不需要。 開門

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM