[英]reading a specific line from one file using a value from another
我有两个文件。 一个文件包含多行数字。 另一个文件包含文本行。 我想从数字列表中查找特定的文本行。 目前我的代码看起来像这样。
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)
获得的行。 但是您不想要行的文本值,而是它们的 integer 值,并且您希望经常搜索容器,这意味着集合会更好。 最后,我会写:
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)
您需要阅读a_file
的内容以获取数字。
像这样的东西应该工作:
lines_to_read = [int(num.strip()) for num in a_file.readlines()]
这将为您提供文件中的数字列表 - 假设每行包含一个要查找的行号。
此外,您不需要将其放入循环中。 它应该 go 在循环之外- 即在它之前 - 这些数字一旦从文件中读入就固定了,因此无需在每次迭代中再次处理它们。
我只会这样做...
a_file = open("numbers.txt")
b_file = open("keywords.txt")
keywords_file = b_file.readlines()
for x in a_file:
print(keywords_file[int(x)-1])
这会读取关键字文件的所有行以将数据作为列表获取,然后遍历您的 numbers 文件以获取行号,并将这些行号用作数组的索引
socal_nerdtastic 帮助我找到了这个解决方案。 非常感谢!
# first, read the numbers file into a list of numbers
with open("numbers.txt") as f:
lines_to_read = [int(line) for line in f]
# next, read the keywords file into a list of lines
with open("keywords.txt") as f:
keyword_lines = f.read().splitlines()
# last, use one to print the other
for num in lines_to_read:
print(keyword_lines[num])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.