单词搜索程序(Python)

时间:2017-12-12 08:32:21

标签: python

我正在开发一个单词搜索程序,该程序读取文件并将文件中给定数量的字符串转换为单词搜索板以及要搜索的单词列表。我的程序主要是工作,但我不知道如何找到列表中单词的结束位置。

我的代码:

def print_it_out(lines, words):
    for direction, tuple in lines.items():
        string = ''.join([i[0] for i in tuple])
        for word in words:
            if word in string:
                coordinates = tuple[string.index(word)][1]
                #print(word, 'starts at', coordinates[0], 'and column', coordinates[1], direction + ".")
                print(word, 'starts at (%d, %d)' % (coordinates[0], coordinates[1]))


def find_words(file_input, words):
    with open(file_input) as file:
        for line in file:
            line = line.replace(' ', '')
            line = line.strip()
            if len(line) == 0:
                for line in file:
                    line = line.replace('\n', '')
                    line = line.lower()
                    words.append(line)
    words = [x.upper() for x in words]
    words = sorted(words)
    print(words)


def get_search_board(file_input, search_board):
    with open(file_input) as file:
        for line in file:
            if len(line.strip()) == 0:
                break
            elif len(line) > 6:
                # line = line.replace('\n', '')
                line = line.lower()
                search_board += line
    search_board = search_board.rstrip()
    search_board = search_board.replace(' ', '')
    length = search_board.index('\n') + 1
    return search_board, length


def main():
    words = []
    search_board = ''
    file_input = input('Enter the name of the file that contains the word search: ')
    find_words(file_input, words)
    search_board, length = get_search_board(file_input, search_board)

    letters = [(letter, divmod(index, length))
               for index, letter in enumerate(search_board)]
    # Reorder the list to represent each reading direction,
    # and add them all to a dictionary
    lines = {}
    offsets = {'down': 0, 'right down': -1, 'left down': 1}
    for direction, offset in offsets.items():
        lines[direction] = []
        for i in range(length):
            for j in range(i, len(letters), length + offset):
                lines[direction].append(letters[j])
            lines[direction].append('\n')
    lines['left'] = letters
    lines['right'] = [i for i in reversed(letters)]
    lines['up'] = [i for i in reversed(lines['down'])]
    lines['left up'] = [i for i in reversed(lines['right down'])]
    lines['right up'] = [i for i in reversed(lines['left down'])]
    # Make strings from the letters, find the words in them and retrieve
    # their original locations

    print_it_out(lines, words)


main()

我正在使用的给定文件:

15 15
J H C J B E H U C Y M J A L Q
N Q Q H K C B V T E X U F A E
W O T A X E J K G N B P V M D
C H C O U I R D P O F X X Z B
Q M F R C P L P B H X K S L S
H L I E A R F C Q V O H M D D
K V F V P E A S Y Q P Z O J L
H K Z N L T V G P C N G H D L
R R Z V B S H D S M X Y T L B
N A A R D A G G Q S I S D N A
O Y F W O M W E I L P X J R Z
Y D F C R W O S A U Z Y O T W
K H M E E A L N C C G X L F B
L Z F F S K Q I E L A R S S B
X Z O H P D M J W Y C V D P A

BOBCAT
CAKE
cat
easy
HONEY
MASTERPIECE
MONEY
PEASY

为了澄清,我的程序能够通过坐标找到每个给定的单词及其起始位置,但是,我也希望能够找到每个单词的结尾/最后一个坐标。除此之外,我希望按字母顺序打印出每个单词的相应坐标。如果您有任何建议,我们表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:0)

这应该这样做。

from collections import Counter

file = open(r"C:/Users/rschuell/Desktop/test.txt", "r", encoding="utf-8-sig")
wordcount = Counter(file.read().split())
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
print (word,wordcount)
file.close();
for item in wordcount.items(): print("{}\t{}".format(*item))