简体   繁体   English

如何在 Python 的 a.txt 文件中查找包含特定字母的单词?

[英]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.我目前正在尝试创建一个程序来找到 nytimes 游戏“拼字蜜蜂”的所有可能答案我的目标是编写一个程序,它接收 7 个输入(游戏中每个字母一个),并从这些输入中找到单词在包含这些字母的 words.txt 文件(带有英文词典)中。 The rules are as follow: the words have to be 4 letters or more, and "middle_letter" has to appear it every words.规则如下:单词必须是4个字母或更多,并且“middle_letter”必须出现在每个单词中。

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.唯一的问题是我得到的 output 是 .txt 文件中包含这些字母和其他字母的每个单词,而我只想要包含特定字母的单词,没有别的。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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