簡體   English   中英

使用來自另一個文件的值從一個文件中讀取特定行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM