用python从大型文本文件中快速提取信息

用python从大型文本文件中快速提取信息,python,performance,memory-management,text-files,Python,Performance,Memory Management,Text Files,我正在尝试做一个脚本,可以搜索文档中的特定键。文档有时可能非常大,因为我希望能够非常快速和高效,并尽可能使用最小的内存量 这是我的密码 Keys=('key1','key2','key3','key4','key5',...,'keyN') LKeys=list(Keys) with open('test.txt', 'r') as inF: for (N,line) in enumerate(inF): if any(x in line for x in LKeys):

我正在尝试做一个脚本,可以搜索文档中的特定键。文档有时可能非常大,因为我希望能够非常快速和高效,并尽可能使用最小的内存量

这是我的密码

Keys=('key1','key2','key3','key4','key5',...,'keyN')
LKeys=list(Keys)

with open('test.txt', 'r') as inF:
   for (N,line) in enumerate(inF):
      if any(x in line for x in LKeys):
           for k in LKeys:
               if k in line:
                  print N,k,line
                  print inF.next().strip() 
                  # Depending of the key sometimes I need to print next N lines
                  #Or do something else with the line for example save the next element after the key in a dictionary or database 
                  LKeyword.remove(k)
inF.close()
test.txt可以是这样的

sdjskjd key1 jdjdjjd : 4
sdjskjd key2 jdjdjjd: 3 hdhdhd:NaN 

sdjskjd key4 jdjdjjd:
dfdgdfdfdffddfdf2t3h
dfdfdfdfdf5dfd3fhth21
dfdfdfdgghhgdhhghjh
.
.
.
sdjskjd keyN jdjdjjd : 1213.5678 Inz:Joe 
例如:

Author  Antoine de Saint-Exupéry
Original title  Le Petit Prince
Translator  (English editions)
Katherine Woods
T.V.F. Cuffe
Irene Testot-Ferry
Alan Wakeman
Richard Howard[1]
David Wilkinson
Illustrator Antoine de Saint-Exupéry
Cover artist    Antoine de Saint-Exupéry
Country France
Language    French
Publisher   Reynal & Hitchcock (U.S.)
Gallimard (France)[2]
Publication date
September 1943 (U.S.: English & French)
(France, French, 1945)[2][Note 1]
Preceded by Pilote de guerre (1942)
Followed by Lettre à un otage (1944)

Author  Jostein Gaarder
Original title  Sofies verden
Country Norway
Language    Norwegian
Genre   Philosophical novel
Publisher   Berkley Books, Farrar, Straus and Giroux (original hardcover), MacMillan (audio)
Publication date
1991
Published in English
1994
Media type  Print (hardcover & paperback) and audiobook (English, unabridged CD & download)
Pages   518 pp
ISBN    978-1-85799-291-5
ISBN 978-1-4272-0087-7
ISBN 978-1-4272-0086-0
OCLC    246845141
LC Class    MLCM 92/06829 (P)

Auteur  Gabriel García Márquez
Pays    Drapeau de la Colombie Colombie
Genre   Roman
Réalisme magique
Version originale
Langue  Espagnol
Titre   Cien años de soledad
Éditeur Editorial Sudamericana
Lieu de parution    Buenos Aires
Date de parution    1967
Version française
Traducteur  Claude et Carmen Durand
Éditeur Éditions du Seuil
Lieu de parution    Paris
Date de parution    1968
Couverture  Élizabeth Butterworth
Nombre de pages 437
ISBN    202023811X
我读到,一个简单的迭代来按顺序访问行,有时是搜索和匹配大型文档所需内存较少的方法,有时比regex更快

关于我的键的一些注释通常会按顺序出现在我的文档中,如果找到了键,则不会再次出现,因为我会将其从列表中删除。但是,在某些情况下,并非所有键都出现在文档中,但如果找到了键2,然后找到了键4,则可能是键3不在文档中。此外,键是不可变的,在文档中显示为精确的单词


有没有更好、更高效、更干净的方法来构造代码?

因此,下面的代码不是使用元组或键列表,而是使用集合。因此,这意味着如果有数千个键,则查找仍将在固定时间内进行。而在列表中,如果您输入['key',…,'keyN']

对于每一行,我们在空格上拆分单词,以便在键中进行查找。如果这个词存在,我们就可以打印出来。如果需要从键中删除键,则必须收缩拆分的单词并再次检查

但是,由于检查集合中的密钥是在固定时间内进行的,因此,出于效率原因,实际上不必删除密钥

考虑到一行中只能有这么多单词,这样做更有效。但可能有N把钥匙

keys = {'key1','key2','key3','key4','key5',...,'keyN'}

with open('test.txt', 'r') as f:
    for no, line in enumerate(f):
        words = line.split()
        for word in words:
            if word in keys:
                print(no, line)
                # find out which word actually matched by repeatedly 
                # shrinking a copy of the list words. 
                # then you could remove the key from keys
此外,您不需要关闭该文件。上下文管理器(ie with)负责在文件被读取后关闭文件

在文本文件中搜索关键字 我对你的密码做了一些调整。我不知道这是不是你一直在寻找的,但不管怎样,这是有效的

Keys = ('Cover', "Cuffe")


with open('test.txt', 'r', encoding="utf-8") as inF:
    for (N, line) in enumerate(inF):
        if any(x in line.split() for x in Keys):
            for k in Keys:
                if k in line.split():
                    print("(line)", N,
                          "(key)", k,
                          "(result)", line)
输出(使用txt文件示例中的数据)为:

(线)4(关键)袖口(结果)T.V.F.袖口

(行)10(键)封面(结果)封面艺术家安托万·德 圣埃克苏佩里

Python2.7版本
如果一个关键字重复了不止一次,但我只需要第一次匹配的数据怎么办?例如,如果键是key={'Author','Language','Version',},我只需要第一本书的信息,恐怕我不明白。在你的问题中给出一个更好的例子?如果你使用open。。。
Keys = ('Cover', "Cuffe")

with open('test.txt', 'r', encoding="utf-8") as inF:
    for (N, line) in enumerate(inF):
        if any(x in line.split() for x in Keys):
            for k in Keys:
                if k in line.split():
                    print "(line)", N,
                          "(key)", k,
                          "(result)", line