选择由字符串列表指定的文件的行

时间:2016-05-31 14:57:45

标签: python string list file

我有一些字符串的python列表。我还有一个文本文件(比如X),其中每一行都有一个单词标记和一些浮点数,然后用空格分隔。每行中的浮动数是不变的。

我的目标是只取与列表中的字符串对应的行,并将其保存为文本文件。如果列表中的任何字符串在文件X中不存在,那么其相应的浮点数应该是随机的,介于-1和1之间。

玩具示例:

list = ['the','in','red']

档案X:

in 0.5 -0.1 -0.6             
good 0.2 0.4 -0.3            
on 0.4 0.6 0.6  
the 0.01 -0.05 0.5  

我想要的新文本文件:

the 0.01 -0.05 0.5  
in 0.5 -0.1 -0.6  
red -0.2 0.3 0.7

该列表有大约400000个字符串,文本文件大约有300万行 请建议一个有效的方法来做到这一点。非常感谢任何建议,谢谢。

1 个答案:

答案 0 :(得分:0)

如果要在一个文件中找到,可以使用grep。

### let's create a file find_strings.py

import os

list = ['the','in','red']
for l in list :
   os.system('grep ' + str(l) + ' fileX.txt')

### after saving the file, run the below command in the console . 
### $ python find_strings.py > list_found_strings.txt