【问题标题】:Outputting line of string search in python在python中输出字符串搜索行
【发布时间】:2017-01-01 16:21:24
【问题描述】:

我是 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")

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

【问题讨论】:

  • 这里的代码存在许多基本问题。但大多数情况下,您永远不会尝试调用searchNoCase(),因此不会打开任何文件。不过,这段代码距离运行还有很长的路要走。
  • 哦,是的。除了调用 searchNoCase(),我还缺少什么?
  • 好吧,1) searchWord(stuff) 绝对什么都不做 - 它会返回您发送给它的任何价值。 2) 文件 2 中的任何代码都不会运行,因为您没有调用该函数。 3)if searchWord() in f:为什么要在文件中找函数? 4)缩进在searchNoCase()中到处都是。还有更多。我认为您会发现更容易专注于在单个文件中完成任务。
  • 这就是重点。我想在文件 2 中定义一个特定的字符串。然后通过调用函数 searchWord 传递该字符串。最后根据定义的字符串搜索文档并输出结果。我想将其作为两个单独的文件进行
  • 我理解这一点,但与此同时,对一些基本的 Python 概念存在根本性的误解。您想从另一个脚本调用此函数这一事实进一步增加了您必须学习的概念列表(例如,您是否有一个 __init__.py 文件?您知道为什么必须使用 if __name__ == '__main__': 吗?)。专注于获得正确的函数并且可以在单个脚本中完成工作,然后担心主要任务。

标签: python string search


【解决方案1】:

我不使用 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()

【讨论】:

  • 优秀。非常非常感谢!
猜你喜欢
  • 2012-09-09
  • 2015-05-28
  • 1970-01-01
  • 2019-12-15
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多