Python:从另一个 .txt 中提取与某个单词匹配的几行(类似于 grep 函数)

2024-09-28 21:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的Python世界,所以原谅我,如果我说一些愚蠢的事情。。。 我的脚本有问题,我有一个巨大的电台列表(我称之为巨大的\u list.txt),看起来像这样:

1ULM MIDAS4 2003.4497 2019.1075 15.6578 5496 4984   7928 -0.013284 -0.000795    
20NA MIDAS4 2008.2355 2017.4511  9.2156 2793 2793   5010  0.031619  0.059160    
21NA MIDAS4 2008.2355 2017.4648  9.2293 3287 3287   5891  0.031598  0.059243    
25MA MIDAS4 2013.3717 2019.1075  5.7358 2007 1279   1398 -0.010216  0.016478    
299C MIDAS4 2003.0308 2007.0856  4.0548 1407 1407   2159 -0.003861 -0.021031
2TRY MIDAS4 2012.0465 2013.6564  1.6099  564  437    437  0.018726  0.054083

线路的前四个字母是站名(例如25MA,299C…)。我创建了一个带有一些站点名称的.txt(我称之为“station\u list.txt”),如下所示:

20NA
21NA
2TRY

等等

我要做的是创建一个.txt文件,其中包含与station\u name.txt中的站名匹配的大型\u list.txt行。我可以这样做,但只对电台列表中的一个项目:

with open ("station_name.txt", "r") as p:
    item='20NA'

def lines_that_start_with(string, fp):
    return [line for line in fp if line.startswith(string)]

with open ("station_line.txt", "w") as l:
    with open ("C:\huge_list.txt","r")as fp:
        for line in lines_that_start_with (item, fp):
            print line
        l.write (line)
l.close()

我怎样才能让它运行在我的电台列表的每一项


Tags: nametxt列表thataswithlineopen
2条回答

您只需将station_name.txt文件读入一个列表,打开huge_list.txt文件并拆分行,然后查看第一个元素是否在列表中。如果是,则将该行写入新文件

stations = [line.rstrip("\n") for line in open("station_name.txt")]

l = open("station_line.txt", "w")
with open("huge_list.txt", "r") as fp:
    for line in fp.readlines():
        if line.split()[0] in stations:
            l.write(line)


# Your huge list will be input.txt
# Your station list will be input2.txt

In [3]: inp1 = open('input.txt')                                                                                                                                                                            

In [4]: inp2 = open('input2.txt') 

# if you don't want to hold anything in memory then this will be hacky solution, memory consuption is also less
with open('input') as inp1:
   for i in inp1: 
      if any([i.startswith(j) for j in inp2]): print(i)

# Result 
25MA MIDAS4 2013.3717 2019.1075 5.7358 2007 1279 1398 -0.010216 0.016478

299C MIDAS4 2003.0308 2007.0856 4.0548 1407 1407 2159 -0.003861 -0.021031   

# if you want to do some kind of work on filtered data it is better to store it in memory
In [5]: inp1 = {i.split(' ',1)[0] :i.split(' ',1)[1] for i in inp1}

# The above lines read your huge file and convert into key-value pair dict
# result will be something like this.

In [6]: inp1                                                                                                                                                                                                
Out[6]: 
{'1ULM': 'MIDAS4 2003.4497 2019.1075 15.6578 5496 4984 7928 -0.013284 -0.000795\n',
 '20NA': 'MIDAS4 2008.2355 2017.4511 9.2156 2793 2793 5010 0.031619 0.059160\n',
 '21NA': 'MIDAS4 2008.2355 2017.4648 9.2293 3287 3287 5891 0.031598 0.059243\n',
 '25MA': 'MIDAS4 2013.3717 2019.1075 5.7358 2007 1279 1398 -0.010216 0.016478\n',
 '299C': 'MIDAS4 2003.0308 2007.0856 4.0548 1407 1407 2159 -0.003861 -0.021031\n',
 '2TRY': 'MIDAS4 2012.0465 2013.6564 1.6099 564 437 437 0.018726 0.054083'}

# similarly, we are going to do for the station file but slightly a different data structure

In [22]: inp2 = set([i.strip() for i in inp2])

# inp2 will look like 

In [23]: inp2                                                                                                                                                                                               
Out[23]: {'25MA', '299C'}

# so to get your result filter the input list based on the station set. 

In [24]: res = {k:v for k,v in inp1.items() if k in inp2}                                                                                                                                                   

In [25]: res                                                                                                                                                                                                
Out[25]: 
{'25MA': 'MIDAS4 2013.3717 2019.1075 5.7358 2007 1279 1398 -0.010216 0.016478\n',
 '299C': 'MIDAS4 2003.0308 2007.0856 4.0548 1407 1407 2159 -0.003861 -0.021031\n'}



# Hope this answer helps you

相关问题 更多 >