首页 > 解决方案 > 解析txt文件以查找单词出现python

问题描述

我对python相当陌生,并为自己找到了一个个人项目。我正在尝试解析一个大文本文件以查找单词出现,但我似乎无法让代码工作。它是这样开始的:

    file = 'randomfile.txt'
    with open(file) as f:
       word = input("Enter a word: ")
       line = f.readline()
       num_line = 1
       while line:
           if word in line:
               print("line {}: {}".format(num_line, line.strip()))
       print("Here are ___ I found with the word" + word)
       num_line += 1
    f.close()

这段代码会运行,但它不会给出搜索词的输出,我看不出为什么不输出的原因,除非 python 没有读取路径中的文本文件,或者第四行代码没有被正确读取?我该如何解决这个问题?

标签: python

解决方案


这将起作用:

with open(randonfile.txt",'r') as f:
   word = input("Enter a word: ")
   line = f.readline()
   num_line = 1
   for words in line.split():
       if word in words:
           print("line {}: {}".format(num_line, line.strip()))

   print("Here are ___ I found with the word" + word)
   num_line += 1

推荐阅读