2

我有包含几千个单词的文本文件(一行一个单词)。我编写了一个函数,它接受两个单词(字符串),并检查一个单词是否是另一个单词的 Anagram(这意味着这两个单词是否包含相同的字母,即使顺序不同)。

现在我想查看我的巨大文本文件并搜索字谜。我的输出应该是一个列表,其中包含几个单词的元组,这些单词是字谜。

问题是我不知道如何使用 for/while 循环遍历单词。我尝试过的一切都失败了。(我很清楚这样做的方式,但我只是不太了解python)。

编辑#1:假设我想遍历文本中的第 1 到 100 行而不是整个文本,我该怎么做?

4

6 回答 6

2
file = 'file.txt'
with open(file, 'r') as f:
    for line in f:
        pass
于 2011-11-25T13:24:04.250 回答
0

readlines 为您提供文件中所有单词的列表:

text = open("myfile.txt")
wordlist = text.readlines()

现在你只需要执行 for 循环:

for item in wordlist:
    anagramfunction()...
于 2011-11-25T13:21:45.127 回答
0
  1. 将所有单词(行)加载到列表中,而单词位于单独的行中,这可以通过以下方式完成readlines()(您必须使用strip()删除行尾):

    words = [s.strip() for s in f.readlines()]

  2. 为每个单词创建字谜

  3. 对该字谜使用单词列表in运算符来检查字谜是否存在
  4. 如果存在则打印
于 2011-11-25T13:23:40.903 回答
0

我会去做这样的事情:

wordList = []
anagrams = []

file = StringIO.StringIO(open("file.txt","rb"),dialect=csv.excel) //Using csv.excel as each word is on a different line, so hoping this should work but Im not entirely sure
wordList.extend(wordList)

Wordlist 现在应该类似于 [Word1, Word2, Word3]

for i in xrange(wordList):
    if wordList[i] == wordList[i+1]://Code to analyse anagrams here
        anagrams.append(wordList[i])

我真的不确定这种语法,我让你知道我会做什么。虽然有人可能会否决这个答案,因为它不在我的脑海中,你必须阻止它抛出 OutOfBounds 错误,但我没有太多时间来写它!:P

于 2011-11-25T16:56:39.850 回答
0

Python 教程涵盖了:

读取行的另一种方法是遍历文件对象。这是内存效率高,速度快,并导致更简单的代码:

for line in f:
    print line,

您可以使用itertools.combinations获取所有单词组合:

with open("file.txt") as word_list:
    for (word1, word2) in itertools.combinations(word_list, 2):
        if anagram(word1, word2):
            # do stuff
于 2011-11-25T13:19:37.783 回答
0

我假设您的单词列表不是那么大,它不适合 RAM。这是一个(未优化的)算法,可以构建字谜列表(使用先前答案的位):

def buildAnagramsList(word, wordList):
    anagramsList = []
    for word2 in wordList:
        if areAnagrams(word, word2): #you already have a similar method
            list.remove(word2) # Spare some time here by not looking twice for the same anagrams
            anagramsList.append(word2)
    return anagramsList

file = open("myfile.txt")
words = [s.strip() for s in file.readlines()]
anagramsLists = [buildAnagramsList(word, words) for word in words]
于 2011-11-25T14:21:37.477 回答