Make a list of words from text file and search these words by letters from input
Ok, I'm a newbie so I appreciate any clues and hints. This is my first question here, so sorry about anything messy! I have found a lot of help with other types of lists and magic tricks, and some things, but not much, that I can use in this one.
I want to make a list from my little text file (containing all the words in the universe). First I want the user to write some letters, then I want to list words which contain these letters. The letters being "abcdeir" for example, the list would go "bad", "bar", "bear开发者_如何学God", etc.
Here is what I have so far:
file = open("allthewords.txt", "r")
I'd use sets for this:
letters = set("abcdeir")
with open("allthewords.txt", "r") as f:
for word in f:
if set(word) <= letters: # check that all letters of `word` are in `letters`
print word
You can tweak this as required.
You can simply write it out in pseudocode, and then execute it:
letters = "abcdeir" # Alternatively, letters = raw_input('Input letters: ')
with open("allthewords.txt", "r") as file:
for word in file:
if all(character in letters for character in word):
print(word)
You can use regexp if in your file some words would be in a same line.
import re
with open('your_file.txt','r') as f:
print re.findall(r"\b[abcdeir]+\b", f.read())
精彩评论