如何在另一个字符串中搜索字符串?

时间:2015-08-20 01:49:19

标签: python

我正在尝试创建一个简单的单词搜索程序。

我已成功打开包含单词搜索网格的外部文件。我还成功打开了一个包含要搜索的单词的文件。我已将网格的每一行存储在列表中,并将文件中的每个单词存储在名为words[]的列表中。

我试图在网格的每一行中搜索单词。我的代码目前不会在网格的每一行中搜索该单词。

gridlines_horizontal = []
gridlines_vertical = []
words = []
not_found = []
found_words = {}

def puzzle(fname) :
    print ""

    for line in f :
        gridlines_horizontal.append(line)

    for line in gridlines_horizontal :
        print line,

    for item in zip(*(gridlines_horizontal[::-1])):
        gridlines_vertical.append(item)

在这里,我试图让words[]中的每个单词一次一个,看看单词是否在单词搜索网格的任何一行中。如果单词出现在任何一行中,那么我就会尝试打印这个单词。代码目前没有这样做。

def horizontal_search(word,gridlines_horizontal) :
    x = 0
    for line in gridlines_horizontal :
        if words[0] in line or words[0] in line[::-1]:
            found_words.update({words[0]:" "})
            print words[0]
        else :
            not_found.append(words)

        x = x + 1

def vertical_search(word,gridlines_vertical):
    x = 0
    for line in gridlines_vertical:
        if words[x] in line or words[x] in line[::-1]:
            print words[0]
            found_words.update({words[x]:" "})
        else:
            not_found.append(words[x])

        x = x + 1

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

    break

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

print ""        

while True:
    try:  
        fname2 = input("Enter a filename for your words between double quotation marks: ")
        with open(fname2) as f:
            for line in f:
                words.append(line)

            """ line in words:
                line = lin   """   

    break

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

2 个答案:

答案 0 :(得分:1)

您的代码中有几个错误:
- 你在使用单词[x]方面并不一致,在你的代码中你想要用单词[x] BUT 替换每个单词[0]
- 这不是必要的,因为你可以使用嵌套的' for'环路。

所以对于横向搜索:

def horizontal_search(words,gridlines_horizontal):
    for word in words:
        for line in gridlines_horizontal:
            if word in line or word in line[::-1]:
                found_words.update({word : " "})
                print(word)
                break
            else:
                not_found.append(word)

答案 1 :(得分:0)

你看过find吗?

a = 'this is a string'
b = 'string'

if (a.find(b) > -1):
    print 'found substring in string'
else:
    print 'substring not found in string'
上面代码的

Live演示

修改

我不确定它是否是拼写错误,但您传递word作为参数而不是words

def horizontal_search(word,gridlines_horizontal) :
x = 0                   ^----------------------------------  
for line in gridlines_horizontal :                        |
    if words[0] in line or words[0] in line[::-1]:        |
         ^-- see here  <------------not matching here -----

def vertical_search(words,gridlines_vertical)的类似问题: