python - 使用来自另一个文件的值从一个文件中读取特定行
问题描述
我有两个文件。一个文件包含多行数字。另一个文件包含文本行。我想从数字列表中查找特定的文本行。目前我的代码看起来像这样。
a_file = open("numbers.txt")
b_file = open("keywords.txt")
for position, line in enumerate(b_file):
lines_to_read = [a_file]
if position in lines_to_read:
print(line)
数字中的值看起来像这样..
26
13
122
234
41
关键字中的值看起来像(示例)
this is an apple
this is a pear
this is a banana
this is a pineapple
...
...
...
我可以手动写出这样的值
lines_to_read = [26,13,122,234,41]
但这违背了使用 a_file 查找 b_file 中的值的意义。我尝试过使用字符串和其他变量,但似乎没有任何效果。
解决方案
[a_file]
是一个包含一个元素的列表,即a_file
. 您想要的是一个列表,其中包含您可以使用a_file.readlines()
或获得的行list(read_lines)
。但是您不想要行的文本值,而是它们的整数值,并且您希望经常搜索容器,这意味着集合会更好。最后,我会写:
lines_to_read = set(int(line) for line in a_file)
现在很好:
for position, line in enumerate(b_file):
if position in lines_to_read:
print(line)
推荐阅读
- c++ - 创建系统托盘右键菜单C++
- r - 可视化 bife 包中的 APE(又名 AME)
- vb.net - 准确复制 Certutil.exe 的 -decodehex 输出
- ios - 如何使用 UICollectionViewCompositionalLayout 获取水平滚动百分比?
- raster - 通过纬度/经度访问 EUMETSAT 栅格?
- node.js - MongoDB NodeJS 错误:assert.equal(3, result.result.n) 不起作用。给出错误“无法读取未定义的属性'n'”
- node.js - 在 node.js 中使用 get 和 post 方法进行路由而不使用 express
- git - 为什么我不能从 master 创建一个 Git 分支?
- c++ - wcsrtombs_s 中可能存在的错误
- asp.net - 从指向文件服务器的虚拟目录读取文件