python - 解析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 没有读取路径中的文本文件,或者第四行代码没有被正确读取?我该如何解决这个问题?
解决方案
这将起作用:
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
推荐阅读
- android - 数据绑定 - 访问 LiveData 中包含的各个属性
- c++ - 递归检查数字是否是完美素数c ++
- javascript - Heroku 日志未加载
- angular - 预检响应没有 HTTP ok 状态。Angular 6 中的 403
- java - 类型不匹配:无法从 String 转换为 int - java
- c - Shanks 的方形分解实现
- javascript - 未知的 301 重定向反应路由器
- c# - 从 ListViewItem 上的按钮获取索引
- drupal - Drupal 8将变量从父段落传递到树枝文件中的子段落
- javascript - 如何在 JSDoc typedefs 中干燥相似的属性