[英]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
這是您想通過算法執行的操作:
這將建議您使用哪種控制流程? 想一想。
我不確定您是否從解決問題的角度或從Python的角度來解決這個問題,但是如果您不確定如何在Python中專門做到這一點,則可以使用以下有用鏈接:
len()
函數 ,可用於獲取字符串,列表,集合等的長度。 我的問題是我怎么打開文件
使用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()
。
看到您的代碼示例后的進一步評論:
print()
語句。 bacon sandwich
而不是數字,該怎么辦? (您的作業可能沒有指定您應該適當地處理錯誤的用戶輸入,但是思考它不會有任何傷害。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.