开发者

Python wordlist

开发者 https://www.devze.com 2023-04-06 08:39 出处:网络
I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know开发者_Go百科 i only have a pri

I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know开发者_Go百科 i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?).

def ordlista(list):
    fil = open("ord.txt", "r")
    words = fil.readlines()

    list = []

    for w in words:
        w = w.strip()
        list.append(w)
    return list


chars = {}
word = raw_input("Write 9 letters: ")

for w in word:
    w = w.lower()
    if w not in chars:
        chars[w] = 1
    else:
        chars[w] += 1


if chars.keys() in ordlista(list):
    print "YES"
else:
    print "NO"


chars.keys() is a list, so

chars.keys() in ordlista(list):

will never be True. What you want is match the letter counts against each word in your list. So I'd suggest

charsum = sum(chars.values())
for word in wordlist:
    if len(word) == charsum and all([(word.count(c) == chars[c]) for c in chars]):
        print "YES for word '%s'" % word

EDIT: If you want those words to match which have at least the letter counts (i.e. a word with 3 a's will match an input of two a's), then you'll have to change the == to a >=.

EDIT2: Since you want exact matches, the easiest solution would be to count the number of chars and make sure the word has that length.


You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.

for k in chars:
    if k in ordlista(list):
        print "YES"
    else:
        print "NO"

If you want to print the words which consist solely of the letters in your character list, you may use the following approach.

for word in ordlista(list):
    if not filter(lambda char: char not in chars, word):
        print word


Use sets:

chars = set(raw_input("Write 9 letters: "))

for word in ordlista(None):
    if(set(word) == chars):
        print "YES for '%s'" % word

BTW, the argument list to ordlista is unnecessary, as it is not used. I would also advise against using the name list in general, because it hides the built-in <type 'list'>

Update: I have read your comment on jellybean's post. If every letter can only be used once, you can obviously not use sets!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号