簡體   English   中英

Python 3.3:Anagram函數的輸出

[英]Python 3.3: Output of Anagram Function

def anagram(word,check):  
    for letter in word:  
        if letter in check:  
            check = check.replace(letter, '') 
        else:  
            return 0  
    return 1  


while True:
    f = open('dictionary.txt', 'r')
    try:
        user_input = input('Word? ')
        for word in f:
            word = word.strip()
            if len(word)==len(user_input):
                if word == user_input:
                    continue
                elif anagram(word, input):
                    print (word)
                    #try:
                        #if word == 1:
                            #print ('The only anagram for', user_input, 'is', word)
                        #elif word > 1:
                            #print ('The anagrams for', user_input, 'are', word)
                    #except TypeError:
                        #pass
    except EOFError:
        break
    f.close()

該函數可以按我希望的方式工作,但是我需要輸出幫助。 我希望輸出在一行中,並且措辭應反映找到的字謎的數量。 (即“只有一個字謎”,“字謎是”,“沒有字謎”或“單詞不在詞典中”)代碼中的注釋是我嘗試過的。 謝謝你的幫助。

以我對程序的理解方式,您是否要不斷提示用戶輸入單詞,直到他按Ctrl-D(這會導致EOF錯誤並破壞循環)? 在這種情況下,您應該在循環開始之前僅讀取一次文件,並在其中構造一個列表或一組單詞。 另外,您的try / except語句應僅包含對input的調用,因為這是函數中可能發生此異常的唯一位置。

現在,您的主要問題-計算結果的數量並相應地打印不同的語句,只需使用列表推導即可獲得所有輸入字謎的列表。 然后,您可以計算字謎並將它們連接在一起以形成輸出字符串。

def find_anagrams():
    with open("dictionary.txt", "r") as fileInput:
        words = set(word.strip() for word in fileInput)

    while True:
        try:
            user_input = input("Word? ").strip()
        except:
            break  #you probably don't care for the type of exception here

        anagrams = [word for word in words if anagram(word, user_input)]
        print_results(anagrams)

def print_results(anagrams):
    if len(anagrams) == 0:
        print("there are no anagrams")
    elif len(anagrams) == 1:
        print("the only anagram is %s" % anagrams[0])
    else:
        print("there are %s anagrams: %s" % (len(anagrams), ', '.join(anagrams)))

該代碼唯一缺少的是,使輸入的單詞不屬於結果列表,但可以將其移至anagram函數。 也可以使用內置collections模塊中的Counter類簡化該功能。 此類是一個類似於字典的對象,可以從可迭代對象構造該對象,並將可迭代對象中的每個對象映射到其出現的次數:

>>> Counter("hello") == {"h":1, "e":1, "l":2, "o": 1}
True

因此,我們可以像這樣重寫字謎函數:

from collections import Counter

def anagram(word, check):
    return not word == check and Counter(word) == Counter(check)

您可以使用以下結果創建一個列表:

with open("dictionary.txt", "r") as fileInput:
    user_input = input("Search keyword: ").strip()

    listAnagrams = []
    for line in fileInput.readlines():
       for word in line.split(" "):
           if len(word) == len(user_input):
               if word == user_input:
                   continue
               elif anagram(word, user_input):
                   listAnagrams.append(word)

    if len(listAnagrams) == 1:
        print ('The only anagram for', user_input, 'is', listAnagrams[0])

    elif len(listAnagrams) > 1:   
        print ('The anagrams for', user_input, 'are', ", ".join(listAnagrams))

    else:
        print ('No anagrams found for', user_input)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM