【问题标题】:Find anagrams in a file [closed]在文件中查找字谜[关闭]
【发布时间】:2012-10-11 19:40:10
【问题描述】:

我想要一个程序在文件中查找字谜。例如:

>>>anagram('words.txt', 'top')
top
pot

该文件将包含一长串没有空格的单词。

tapmatlamebrainfamelookcookkoolkoocnamemane

这是我当前的代码:

def anagrams(filename, word):
    infile = open(filename, 'r')
    if not word:
        return ['']
    ret = []
    for i, d in enumerate(word):
        perms = anagrams(word[:i] + word[i+1:])
        for perm in perms:
            ret.append(d + perm)
    for i in ret:
        if i in infile:
            print (i)
        else:
            pass

【问题讨论】:

  • 你希望如何分隔文本文件中的单词以不匹配 glotpaul 之类的内容
  • 现在我运行一个置换函数,然后查找文件中是否有这些函数。但这似乎不起作用,因为它什么也不返回
  • 你的问题很模糊。您能否提供一个示例输入和输出?
  • @inspectorG4dget 顶部再读一遍
  • @JasonSchayer:你的问题仍然模棱两可。你使用itertools.permutations 的目的是什么?你会接受 anagram finder 函数返回的非英语单词吗?

标签: python anagram


【解决方案1】:

这应该做我认为你想要它做的事情

def anagram(filepath, word):
    with open(filepath) as f:
        text = ''.join(line.strip() for line in file)
    for i in xrange(len(text)-len(word):
        prop = text[i:i+len(word)]
        if all(char in word for char in prop) and all(prop.count(char) == prop.count(word) for char in prop):
            print prop

请注意,如果您的文件中只有“hi”和“there”这两个单词作为“hithere”,并且您查找“ith”的字谜,则将打印"hit"

【讨论】:

  • @JasonSchayer:失败的输入是什么?它应该在该输入上产生什么,这与它实际产生的有什么不同?
猜你喜欢
  • 1970-01-01
  • 2015-05-06
  • 2022-01-21
  • 2019-07-07
  • 1970-01-01
  • 2011-12-15
  • 2013-09-20
  • 2013-11-25
  • 2013-07-05
相关资源
最近更新 更多