如何找到单词搜索中找到的单词的确切位置

时间:2015-08-19 18:57:51

标签: python

我的程序读取两个外部文件,一个包含随机单词,另一个包含单词搜索的网格。我的代码从一个文件中读取单词,然后尝试查看是否可以在网格中找到该单词。我的代码可以成功确定网格中当前的单词是否存在。但是我需要打印找到单词的确切位置,例如:

找到活动:第3行第3行到第3行第8行

我不确定如何让程序找到单词的确切出现位置。

print ""

# To God be the Glory

gridlines = []
not_found = []
found_words = {}

# Printing the grid
def puzzle(fname) :     
    print ""    
    for line in f :       
        gridlines.append(line)  
    for line in gridlines :       
        print line,

# Searching for horizontal words    
def horizontal_search(word,gridlines) :
    x = 0  
    for line in gridlines :  
        # Seeing if the word can be found in every line of the grid      
        if word in line or word in line[::-1] : 
            return word

        x = x + 1

        elif word not in line or word not in line [::-1] :        
            return None

            # Putting all the words that are not found in a list

            not_found.append(word)


    # Asking the user to enter a file until the correct file is open

    while True : 
        try:  
            fname = input("Enter a filename between quotation marks : ") 
            with open(fname) as f:
                puzzle(fname)

         print ""        
            while True :       
                try :
                    fname2 = input("Enter a filename between quotation marks : ")

                    with open(fname2) as f:          
                        for line in f :               
                           line = word                     
                           break

        print ""

        # Giving the words from the file to the horizontal word search function

        horizontal_search(word,gridlines)

        break        
        except IOError as e :
            print""
            print("Problem opening file...")

1 个答案:

答案 0 :(得分:0)

您可以按照评论中的建议尝试使用enumerate

keyword = 'w'

gridlines = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'w', 'z']]

def findit(gridlines, keyword):
    for i, line in enumerate(gridlines):
        print i, line
        for j, word in enumerate(line):
            print j, word
            if word == keyword:
                return i, j
i, j = findit(gridlines, keyword)
print 'Word found at line {} and index {}'.format(i, j)

>>> Word found at line 2 and index 1 

使用enumerate可以循环遍历列表,同时在每次迭代时跟踪索引。这应该可以让您找到所需内容的位置。

抱歉,您的问题现在更清楚了。我有这个适用于简单的情况。它会创建一个助行器,在棋盘上四处寻找字母匹配,如果找到所有字母则会返回。

import numpy as np

keyword = list('wol')  # Word to find in crossword

a = np.array([['w', 'b', 'l'],  # The board of the crossword
              ['d', 'o', 'f'],
              ['m', 't', 'd']])

a = np.pad(a, 1, 'constant')

search = [(0,1), (1,0), (1,1), (-1,-1), (-1,0), (0,-1), (-1,1), (1,-1)]

used = set()

starting_positions = np.where(a == keyword[0])
start = zip(starting_positions[0], starting_positions[1])

def find_route(start, search, a, keyword):
    for i in start:
        positions = [i]
        count = 0
        current = i
        for j in keyword[1:]:
            path = []
            for s in search:
                point = (s[0]+ current[0], s[1] + current[1])
                if a[point] == j:
                    path.append(s)                        
                    positions.append(point)
                    if count == len(keyword)-2:
                        return True, [(j[0]-1, j[1]-1) for j in positions]
                    current = point
                    break
                else:
                    break
            count += 1
    return False, []



print find_route(start, search, a, keyword)
>>> (True, [(0, 0), (1, 1), (0, 2)])

print find_route(start, search, a, list('wok'))
>>> (False, [])

print find_route(start, search, a, list('wfd'))
>>> (False, [])

如果您不需要对角线,请更改search参数 您可能需要调试/更改更复杂的板。祝你好运!