簡體   English   中英

在文件中查找特定單詞

[英]Finding specific words in a file

我必須用python編寫程序,為用戶提供帶有四個不同“文字游戲”的菜單。 有一個名為dictionary.txt的文件,其中一個游戲要求用戶輸入a)一個單詞中的字母數和b)一個要從詞典中搜索的單詞中排除的字母(dictionary.txt包含整個詞典) )。 然后程序打印出符合用戶要求的單詞。 我的問題是,究竟該如何打開文件並在該文件中搜索一定長度的單詞。 我只有一個基本代碼,只要求用戶輸入。 我對此很陌生,請幫助:(這是我的首要選擇。其他的都很好,我知道如何打破循環,但是這個特定的問題確實給我帶來了麻煩。我只是不斷出錯,老實說,我上這堂課的原因是有人說這很有趣,但是,最近我真的落后了,不知道現在該怎么做,這是入門課程請很好,我從來沒有做過此事:(

print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print

choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice

while choice != "q":
    if choice == "a":
        #wordlen = word length user is looking for.s

        wordlen = raw_input("Please enter the word length you are looking for: ")
        wordlen = int(wordlen)
        print wordlen

        #letterex = letter user wishes to exclude.
        letterex = raw_input("Please enter the letter you'd like to exclude: ")
        letterex = letterex.lower()
        print letterex

這是您想通過算法執行的操作:

  1. 打開你的文件
  2. 逐行讀取它,並在每一行上(假設每一行只有一個並且只有一個單詞),檢查該單詞是否為a)適當長度,並且b)是否不包含排除的字符

這將建議您使用哪種控制流程? 想一想。

我不確定您是否從解決問題的角度或從Python的角度來解決這個問題,但是如果您不確定如何在Python中專門做到這一點,則可以使用以下有用鏈接:

我的問題是我怎么打開文件

使用with語句

with open('dictionary.txt','r') as f:
    for line in f:
       print line

然后在該文件中搜索具有一定長度的單詞。

首先,確定您要搜索的單詞的長度。

然后,讀取文件中包含單詞的每一行。

檢查每個單詞的長度。

如果它與您要查找的長度匹配,請將其添加到列表中。

要打開文件,請使用open() 您還應該閱讀Python教程sec。 7, 文件輸入/輸出

打開文件並獲取每一行

假設您的dictionary.txt中的每個單詞都位於單獨的行中:

opened_file = open('dictionary.txt')
for line in opened_file:
    print(line) # Put your code here to run it for each word in the dictionary

字長:

您可以使用字符串的str.len()方法檢查其長度。 請參閱有關字符串方法Python文檔

"Bacon, eggs and spam".len() # returns '20' for 20 characters long

檢查單詞中是否包含字母:

再次從Python sring方法使用str.find()


看到您的代碼示例后的進一步評論:

  • 如果要打印多行提示,請使用heredoc語法 (三引號),而不要重復使用print()語句。
  • 如果系統提示您“用戶輸入多少個字母”,而您輸入的是bacon sandwich而不是數字,該怎么辦? (您的作業可能沒有指定您應該適當地處理錯誤的用戶輸入,但是思考它不會有任何傷害。)

暫無
暫無

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

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