[英]Issues when grabbing words of a specific length from a txt file in python
我對我的代碼的主要困惑是我的目標是在 dictionary.txt 中找到所有單詞,特定長度只包含一個元音(定義為 a、e、i、o 和 u),沒有其中的一個特定字母。 但是,它不能正常工作。 例如,如果我要查找所有長度為 9 且僅包含一個沒有字母 't' 的元音的單詞,下面的程序會告訴我“沒有符合此條件的單詞”。 但是文件中應該有兩個詞滿足上述條件:“lynchings”和“lynchpins”。
我的字典位於https://filebin.net/96k7kso4i6nxcd2n/dictionary.txt?t=x9ujn62v
def onevowel(file):
length = int(input("Please enter the word length you are looking for: "))
letter = input("Please enter the letter you'd like to exclude: ")
wordnum = 0
for word in file:
word = word.strip()
if len(word) == length:
count = 0
for char in word:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
count += 1
if count == 1:
flag = 1
word_str = ""
for char in word:
if char == letter:
flag = 0
else:
word_str += char
if flag == 1:
print (word_str)
wordnum += 1
if wordnum == 0:
print ("There are no words that fit this criteria.")
if __name__ == "__main__":
my_file = open("dictionary.txt","r")
onevowel(my_file)
my_file.close()
用char in "aeoui"
替換char=='a' and char=='e' and char=='i' and char=='o' and char=='u'
(這永遠不是真的)。
因為您只需要一個元音,請在此行中使用or
條件而不是and
:
if (char=='a' and char=='e' and char=='i' and char=='o' and char=='u'):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.