简体   繁体   中英

Issues when grabbing words of a specific length from a txt file in python

The main confusion I am having with my code is that I am aiming to find all the words in the dictionary.txt of a particular length containing just a single vowel (defined as a, e, i, o and u) that does not have a particular letter in it. However, it does not work correctly. For example, if I am looking for all the words of length 9 containing just a single vowel that does not have letter 't' in it, the program below tells me “There are no words that fit this criteria”. But there should be two words in the file satisfying the above criteria: “lynchings”, and “lynchpins”.

My dictionary is located at 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'): 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM