【问题标题】:Python3, read specific word from .txt filePython3,从 .txt 文件中读取特定单词
【发布时间】:2018-03-17 11:15:39
【问题描述】:

我想知道如何使用 Python3 在 .txt 文件中搜索特定单词。 如果 .txt 文件中包含单词“pizza”,那么它应该(例如)导入另一个 python 程序。

【问题讨论】:

  • 你的研究建议你应该使用什么?
  • 我没有找到类似的东西
  • 我相信你可以在这里找到答案stackoverflow.com/a/27914129/8362224
  • 如果这没有帮助,edit 你的问题并添加你尝试过的代码,以及为什么它没有达到你想要的效果。见How to Ask

标签: python-3.x


【解决方案1】:

您可以使用'for'循环遍历文件中的每一行并检查字符串是否在该行中:

f = open('file.txt', 'r')
for line in f:
   if 'pizza' in line:
      # do whatever you want here
      print("Found it!")
   else: 
      pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2011-05-20
    • 2014-06-03
    相关资源
    最近更新 更多