在python中输出字符串搜索行

时间:2017-01-01 16:21:24

标签: python string search

我是python的新手,我试图在文本文件中搜索特定的字符串,然后输出包含该字符串的整行。但是,我想将此作为两个单独的文件。主文件包含以下代码;

def searchNoCase():
   f = open('text.txt')
   for line in f:
         if searchWord() in f:
            print(line)
   else:
    print("No result")

   f.close()



def searchWord(stuff):
      word=stuff
     return word

文件2包含以下代码

import main

def bla():
  main.searchWord("he")

我确定这是一个简单的修复,但我似乎无法弄明白。非常感谢帮助

1 个答案:

答案 0 :(得分:0)

我没有使用Python 3,因此我需要确切地检查__init__.py的更改内容,但同时在与以下文件相同的目录中创建一个带有该名称的空脚本。

我试图涵盖一些不同的主题供您阅读。例如,异常处理程序在这里基本没用,因为input(在Python 3中)总是返回一个字符串,但是你需要担心它。

这是main.py

def search_file(search_word):

    # Check we have a string input, otherwise converting to lowercase fails
    try:
        search_word = search_word.lower()

    except AttributeError as e:
        print(e)
        # Now break out of the function early and give nothing back
        return None

    # If we didn't fail, the function will keep going

    # Use a context manager (with) to open files. It will close them automatically
    # once you get out of its block

    with open('test.txt', 'r') as infile:
        for line in infile:

            # Break sentences into words
            words = line.split()

            # List comprehention to convert them to lowercase
            words = [item.lower() for item in words]

            if search_word in words:
                return line

    # If we found the word, we would again have broken out of the function by this point
    # and returned that line
    return None

这是file1.py

import main

def ask_for_input():
    search_term = input('Pick a word: ') # use 'raw_input' in Python 2
    check_if_it_exists = main.search_file(search_term)

    if check_if_it_exists:
        # If our function didn't return None then this is considered True
        print(check_if_it_exists)
    else:
        print('Word not found')

ask_for_input()