首页 > 解决方案 > 检查文件中是否出现特定单词,如果没有打印文件中没有单词

问题描述

下面的代码打开文件并通过读取行​​来检查文件中是否出现特定单词,如果出现则打印该单词所在的行。我不知道如何将最后一行代码更改为仅在文件中根本没有出现特定单词时才打印“文件中没有 {find}”。

word = input('Input the word to find: ')
this_line = 0
find = word
with open (n, 'r') as f:
    read_data = f.readlines()
    last = read_data[-1]

for line in read_data:
    this_line += 1
    if find in line:
        print (f' {find} is in line {this_line}')
        if read_data is last:
            break
            
    print(f' No {find} in file.')

标签: python-3.8

解决方案


解决了:

word = input('Input the word to find: ')
this_line = 0
words = 0
find = word
with open (n, 'r') as f:
    read_data = f.readlines()
    last = read_data[-1]

for line in read_data:
    this_line += 1

    if find in line:
        words +=1
        print (f' {find} is in line {this_line}')
        if read_data is last:

            break

if words == 0:
    print(f' No {find} in {n}.')
else:
    print('--------------------------------')
    print(f'{find} appears {words} times in {n}')

推荐阅读