python-3.8 - 检查文件中是否出现特定单词,如果没有打印文件中没有单词
问题描述
下面的代码打开文件并通过读取行来检查文件中是否出现特定单词,如果出现则打印该单词所在的行。我不知道如何将最后一行代码更改为仅在文件中根本没有出现特定单词时才打印“文件中没有 {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.')
解决方案
解决了:
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}')
推荐阅读
- python - django在upload_to参数上获取字段名
- c++ - 为什么我可以在 C++ 中更改 const 变量?
- android - Android Studio Flutter 显示多个错误
- c# - EF Core 3 中 DBFunction 的动态列名
- sql - 如何计算此列与 2 行的比例
- data-science - 发现样本数量不一致的输入变量:[3080, 770]
- c - 如何加入角色?
- python - Python Flask for 循环不会打印网站上的所有单词
- node.js - HTTP 服务器在响应某些请求时出错
- python - 有没有办法将包含三个列表的元组拆分为其各个元素