简体   繁体   中英

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", "beard", 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())

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