python - 为什么 readline() 没有从我的 .txt 中获取所有单词
问题描述
我正在打开一个文本文件,逐行读取并去除尾随的 '\n' 并将其附加到带有以下代码的列表中。执行此操作时,有些单词会丢失。谁能告诉我为什么?
def compare(t, w):
c = {}
m = []
for line in t:
lines = t.readline()
word = lines.strip()
m.append(word)
for x in m:
c[x] = c.get('x', 0)
if w in c:
print('True')
else:
print('False')
fin = open('words.txt')
compare(fin, 'expect')
解决方案
不要.readline
在for line in t
循环内使用。每次迭代都会读取一个新行,并在 .readline 中读取下一行,因此每次迭代都会跳过一行。
推荐阅读
- java - java12中关于BufferedWriter类的错误
- codeigniter - 根据表单输入下载 zip 文件夹 - Codeigniter
- ruby - 使用 oauth2.0 使用 ruby 在 Box 中刷新回调访问令牌
- sql-server - SQL:在分组对象上执行 MAX 类似 OR
- haskell - monadicIO 的工作原理
- angular - Angular - 从后端获取结果为“Null”
- tcp - 实时 TCP 连接约束
- java - 如何避免具有相同属性名称和不同数据类型的属性的冲突 getter 定义
- node.js - PRISMA:身份验证令牌无效:未提供“授权”标头
- ios - DetoxRuntimeError:Detox 实例尚未初始化