提问者:小点点

如何读取文本文件中的特定单词?


我试图让这个程序读取文本文件中的一个特定单词,但是结果只能是“1”。 为什么会出现这种情况?

import os

openfile = input('Enter the input file: ')
accumulator = 0
entry = "PMID"
if os.path.isfile(openfile):
    file = open(openfile,'r')
    for entry in file.readlines():
        accumulator +=1
        print('there are:',accumulator)
        exit()

print('Input file not found.')
print('Please check the file name or the location of your input file.')

太谢谢你了!


共2个答案

匿名用户

问题是您正在for循环中调用exit()。 这意味着在第一次迭代之后(当accumulator=1),您将结束循环。 将此指令移出循环以使其正常工作。

import os

openfile = input('Enter the input file: ')
accumulator = 0
word = "PMID"

if os.path.isfile(openfile):
    file = open(openfile,'r')

    for entry in file.readlines():
        accumulator +=1

    print(f'There are {accumulator} occurences of "{word}" in {openfile}')

else:
  print('Input file not found.')
  print('Please check the file name or the location of your input 

如果你想计算某个词的出现次数。。。

import os

openfile = input('Enter the input file: ')
accumulator = 0
word = "PMID"

if os.path.isfile(openfile):
    file = open(openfile,'r')

    for entry in file.readlines():
        if word in entry:
            accumulator +=1

    print(f'There are {accumulator} occurences of "{word}" in {openfile}')

else:
  print('Input file not found.')
  print('Please check the file name or the location of your input file.')

匿名用户

您可以尝试如下操作:

for line in file.readlines():
    accumulator += entry in line