python - Python 中的 Anagram 代码 - 将动态生成的字符串与 txt 文件进行比较

标签 python io anagram

我用 Python 编写了一个 Anagram 解决程序。我想听听你对我的做法是否正确的看法。让我解释一下逻辑:

  1. 首先,用户提供两个单词的输入,他/她希望为其生成单个单词字谜(2 个字符串值)
  2. 将这两个值连接起来,得出第三个值。
  3. 第三个值由 itertools.permutations 函数处理,其中单词的所有可能排列都以列表形式导出。
  4. 列表采用从列表派生的字符串值进行格式化。
  5. 此时,我已经打开了一个单词列表,它将用作字典来比较字符串值是否是实际单词。
  6. 逐行读取文件,并将字符串值与行进行比较。
  7. 如果找到匹配项,程序会将输出作为字典匹配项打印在屏幕上

请告诉我我的做法是否正确,或者是否可以提出任何改进建议。任何反馈表示赞赏。我是 Python 新手。

代码如下:

    #This program has been created to solve anagram puzzles

# All the imports go here
#import re
import itertools
import fileinput

def anaCore():
    print 'This is a Handy-Dandy Anagram Solving Machine'
    print 'First, we enter the first word....'
    anaWordOnly = False

    firstWord = raw_input('Please enter the first word > ')
    print 'Thank you for entering %r as your first word' % firstWord
    print 'Now we enter the second word....'
    secondWord = raw_input('Please enter the second word > ')
    print 'Thank you for entering %r as your second word' % secondWord

    thirdWord = firstWord+secondWord

    print thirdWord

    mylist = itertools.permutations(thirdWord)

    for a in mylist:
        #print a
        mystr = ''.join(a)
        for line in fileinput.input("brit-a-z.txt"):       
            if mystr in line:
                print 'Dictionary match found', mystr
        #print mystr

anaCore()

最佳答案

当然,您可以生成所有单词排列。不过,我认为对单词中的字母进行排序会更方便。因此,您必须预处理整个字典,即对每个单词中的字母进行排序。然后,您只需检查字符的排序序列即可。

为了简化:我将生成您的字谜词的排序序列。对于文件中的每一行,我会对它的字符进行排序并检查两者是否相同。如果是,请检查它们是否是相同的单词。如果它们不是相同的单词,那么它们就是字谜。

关于python - Python 中的 Anagram 代码 - 将动态生成的字符串与 txt 文件进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6848548/

相关文章:

python - 使用 AWS Lambda (python) 编写 csv 文件并将其保存到 S3

python - 使用 Pandas 创建绘图并直接显示与使用 Matplotlib 类似的输出

java - Java中的Anagram算法

c++ - 如何在不递归的情况下找到所有可能的字谜?

python - 使用 Python Pandas 跳过 csv 文件中的行

python - 扩展图像字段以允许 pdf ( django )

scala - 如何在Scala中将字符串列表打印为标准错误?

io - 是否有真正的程序检查文件关闭错误?

java - 有谁知道Java中访问磁盘IO队列长度的方法吗?

java - 为什么 for 循环比应有的更早停止?