Skip to main content
 首页 » 编程设计

Python:使用另一个文件作为键从文件中提取行

2025年05月04日15bonelee

我有一个看起来像这样的“ key ”文件 (MyKeyFile):

afdasdfa ghjdfghd wrtwertwt asdf(这些在专栏中,但我从来没有弄清楚格式,抱歉)

我调用这些键,它们与我想从“源”文件中提取的行的第一个词相同。所以源文件 (MySourceFile) 看起来像这样(同样,格式错误,但第一列 = 键,后面的列 = 数据):

afdasdfa(几个制表符分隔的列) . . ghjdfghd(几个制表符分隔的列) . wrtwwtwt . . 阿斯达夫

还有'.'将指示当前不感兴趣的线路。

我是 Python 的绝对新手,这就是我的成就:

with open('MyKeyFile','r') as infile, \ 
open('MyOutFile','w') as outfile: 
    for line in infile: 
        for runner in source: 
            # pick up the first word of the line in source 
            # if match, print the entire line to MyOutFile 
            # here I need help 
outfile.close() 

我意识到可能有更好的方法来做到这一点。感谢所有反馈 - 沿着我解决它的方式,或者沿着更复杂的方式。

谢谢 jd

请您参考如下方法:

我认为这将是一种更简洁的方法,假设您的“ key ”文件名为“key_file.txt”并且您的主文件名为“main_file.txt”

keys = [] 
my_file = open("key_file.txt","r") #r is for reading files, w is for writing to them. 
for line in my_file.readlines(): 
    keys.append(str(line)) #str() is not necessary, but it can't hurt 
#now you have a list of strings called keys.  
#take each line from the main text file and check to see if it contains any portion of a given key.  
 
my_file.close() 
new_file = open("main_file.txt","r") 
for line in new_file.readlines(): 
    for key in keys: 
        if line.find(key) > -1:  
            print "I FOUND A LINE THAT CONTAINS THE TEXT OF SOME KEY", line 

您可以修改打印功能或摆脱它,以使用包含某些键文本的所需行来执行您想要的操作。让我知道这是否有效