【问题标题】:How do I search for a word in a text document and display that line?如何在文本文档中搜索单词并显示该行?
【发布时间】:2013-12-08 17:03:28
【问题描述】:

这就是我目前所拥有的。我需要帮助。我是 python 新手,对它没有太多了解。我需要在文件中搜索某个单词单词,然后当该单词出现在该行中时,它会打印出来。

file = open(input("please input your file name   "))
        word = input("please enter the value you want to search for   ")

    with open(file, 'r') as file:
        for line in file:
            if 'word' in line:
                print (line)

我遇到的问题是了解我需要分配给 with 语句的内容。找到单词和行。目前我在 with 语句中有文件作为文件。我不知道还能放什么。

【问题讨论】:

  • 请准确解释您的代码存在什么问题。问题是什么以及为解决它做了哪些尝试。

标签: python search text


【解决方案1】:

应该是(注意没有引号):

if word in line:

不是

if 'searchphrase' in line:

【讨论】:

  • 我猜你是对的......但这可能是在将代码复制到网站时出错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-29
  • 2021-02-13
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多