user10401694
user10401694

Reputation:

How to print words containing specific letters

I have file with words, each line contain a word. What I try do to is ask user for a letters and search for a words with all these letters user has input. I work on it for a few days but can't make lines 7 and 8 running properly only getting different errors or either is not giving any results.

letters = input('letters: ')
words = open('thesewords').read().splitlines()

print (words)
print(".......................")

for word in words:
    if all(letters) in word:
        print(word)

Upvotes: 0

Views: 1709

Answers (4)

Ricky Rick
Ricky Rick

Reputation: 61

As the there are a lot of Syntax Error in the code, I am trying to re-write the code which you have provided drawing a rough sketch of your objective. I hope the code below will satisfy your demand.

letters = input("letters:" )
words = open("thesewords.txt","r")
for word in line.split():
    print (word)
print(".......................")
for wrd in words:
    if letters in wrd:
        print(wrd)
    else:
        continue

Upvotes: 0

pitamer
pitamer

Reputation: 1064

Try this:

letters = input('letters: ')

# Make sure you include the full file name and close the string
# Also, .readlines() is simpler than .read().splitlines()
words = open('thesewords.txt').readlines()

# I'll assume these are the words:
words = ['spam', 'eggs', 'cheese', 'foo', 'bar']

print(words)
print(".......................")

for word in words:
    if all(x in word for x in letters):
        print(word)

Upvotes: 0

Adarsh TS
Adarsh TS

Reputation: 303

A more simpler solution if you omit all would be:

letters = input('letters: ')
words_in_file = open('thesewords').read().splitlines()

for word in words_in_file:
    if letters in words:
        print(word)

Upvotes: 0

Austin
Austin

Reputation: 26047

You are using all() wrongly. all(letters) is always a True for string letters, and True in <string> returns you a TypeError.

What you should do is:

all(x in word for x in letters)

So, it becomes:

for word in words:
    if all(x in word for x in letters):
        print(word)

Upvotes: 3

Related Questions