简体   繁体   中英

how to find words containing specific letters in a .txt file with Python?

I'm currently trying to create a programm to find all the possible answers to the nytimes game "spelling bee" My goal is to write a programm, which receives 7 inputs (one per letters in the game), and from those inputs finds words in a words.txt file (with the english dictionnary) containing those letters. The rules are as follow: the words have to be 4 letters or more, and "middle_letter" has to appear it every words.

Here is the code that I have at the moment:

middle_letter = input("Entrez la lettre du milieu : ")
l1 = input("Entrez la lettre n°1 : ")
l2 = input("Entrez la lettre n°2 : ")
l3 = input("Entrez la lettre n°3 : ")
l4 = input("Entrez la lettre n°4 : ")
l5 = input("Entrez la lettre n°5 : ")
l6 = input("Entrez la lettre n°6 : ")

with open('words.txt') as f:
    print([w.strip() for w in f if {middle_letter, l1, l2, l3, l4, l5, l6} <= set(w)])

The only thing is that the output I get is every words in the.txt file containing these letters, with other ones, whereas I only want the words containig the specific letters, and nothing else.

Thanks in advance for your precious help:)

The code that ended up working for me is:

middle_letter = input("Enter the middle letter: ")
l1 = input("Enter letter #1: ")
l2 = input("Enter letter #2: ")
l3 = input("Enter letter #3: ")
l4 = input("Enter letter #4: ")
l5 = input("Enter letter #5: ")
l6 = input("Enter letter #6: ")

with open('words.txt') as f: words = [w.strip() for w in f 
if set(w.strip()).issubset({middle_letter, l1, l2, l3, l4, 
l5, l6})]

possible_words = [word for word in words if middle_letter 
in word and l1 + l2 + l3 + l4 + l5 + l6 in ''.join([c for c 
in word if c != middle_letter])]

print(possible_words)

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