我用 Python 编写了一个 Anagram 解决程序。我想听听你对我的做法是否正确的看法。让我解释一下逻辑:
- 首先,用户提供两个单词的输入,他/她希望为其生成单个单词字谜(2 个字符串值)
- 将这两个值连接起来,得出第三个值。
- 第三个值由 itertools.permutations 函数处理,其中单词的所有可能排列都以列表形式导出。
- 列表采用从列表派生的字符串值进行格式化。
- 此时,我已经打开了一个单词列表,它将用作字典来比较字符串值是否是实际单词。
- 逐行读取文件,并将字符串值与行进行比较。
- 如果找到匹配项,程序会将输出作为字典匹配项打印在屏幕上
请告诉我我的做法是否正确,或者是否可以提出任何改进建议。任何反馈表示赞赏。我是 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/