【问题标题】:== comparisons against lines from readlines() fail== 与 readlines() 中的行进行比较失败
【发布时间】:2015-04-13 23:36:11
【问题描述】:

我目前正在开发一个小型 anagram 程序,该程序会获取单词的所有可能排列并将它们与字典进行比较。但是,我无法打印结果。罪魁祸首似乎是 == 运算符,如果我输入 ''.join(words[i]) == compare[j] 则不会打印任何内容,但是,如果我输入 hi 并使用 ''.join(words[i]) == "hi" 运行程序,则会打印整个字典,但如果我将其反转为 "hi" == compare[j] 则不会打印任何内容。

提前感谢您的帮助!

import itertools

run = input("Please enter a word: ")
dictionary = "dictionary.txt" #input("Please enter the name of the dictionary file: ")
txt = open(dictionary)

compare = txt.readlines()

words = (list(itertools.permutations(run)))

for i in range(0, len(words)):
    for j in range(0, len(compare)):
        if ''.join(words[i]) == compare[j]:
            print(compare[j])

【问题讨论】:

  • 请注意,当你说你倒置它时,你没有。我建议您通过打印所有涉及的变量来进行调试。从您目前收集到的信息来看,问题似乎是compare[j]

标签: python anagram readlines


【解决方案1】:
compare = txt.readlines()

readlines() 不会从每行中删除行尾,因此每行的末尾都会有一个\n。这会导致您与 compare[j] 的所有比较都失败。

你可以用类似的东西删除\n

compare = [line.strip() for line in txt]

【讨论】:

    【解决方案2】:

    请注意,如果您的单词包含 W 字母,而您的字典包含 D 单词,那么您的搜索将进行 W! * D 比较。

    您可以通过将这两个词都转换为规范形式(即按字母顺序排列的字母)将其减少为D 比较。

    如果您要搜索 N 单词,您可以通过将字典存储为 {canonical_form: [list,of,matching,words]} 将其进一步减少到每个单词的 D / N 比较(摊销):

    from collections import defaultdict
    
    DICT_FILE = "dictionary.txt"
    
    def canonize(word):
        # "hello\n" => "ehllo"
        return "".join(sorted(word.strip()))
    
    def load_dict(fname=DICT_FILE):
        lookup = defaultdict(list)
        with open(fname) as inf:
            for line in inf:
                word = line.strip()
                canon = canonize(word)
                lookup[canon].append(word)
        # lookup["ehllo"] = ["hello"]
        return lookup
    
    def main():
        anagrams = load_dict()
        while True:
            word = input("Enter word to search for (or hit Enter to quit): ").strip()
            if not word:
                break
            else:
                canon = canonize(word)
                if canon in anagrams:
                    print("Found: " + ", ".join(anagrams[canon]))
                else:
                    print("No anagrams found.")
    
    if __name__ == "__main__":
        main()
    

    然后像这样运行

    Enter word to search for (or hit Enter to quit): tester
    Found: retest, setter, street, tester
    
    Enter word to search for (or hit Enter to quit): binary
    Found: binary, brainy
    
    Enter word to search for (or hit Enter to quit): ttt
    No anagrams found.
    
    Enter word to search for (or hit Enter to quit): 
    

    【讨论】:

      【解决方案3】:

      替换变量中的换行符:

      compare = compare.replace('\n', '')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-05
        • 1970-01-01
        • 2015-06-01
        • 1970-01-01
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        • 2018-06-05
        相关资源
        最近更新 更多