0
  1. 我有几个测试文件保存在一个目录中
  2. 我想转到每个文件并搜索一些文本“文本 1”和“文本 2”并在输出文件中打印此文本前面的所有内容......
  3. 这是我使用python脚本完成的.....
  4. 但接下来我只想要每个文件中“Text 1”和“Text 2”的第一个实例。如果我添加break当前脚本,我将无法打印输出文件..

请指导我..我是python初学者...

import os
path = "D:\test"
in_files = os.listdir(path)
desc = open("desc.txt", "w")
print >> desc, "Mol_ID,   Text1,  Text2"
moldesc = ['Text1', 'Text2']
for f in in_files:
    file = os.path.join(path, f)
    text = open(file, "r")
    hit_count = 0
    hit_count1 = 0
    for line in text:
        if moldesc[0] in line:
            Text1 = line.split()[-1]
        if moldesc[1] in line:
            Text2 = line.split()[-1]
            print >> desc, f + "," + Text1 + "," + Text2
text.close()
print "Text extraction done !!!"
4

2 回答 2

2

您的代码有几个问题:

  • text.close()应该与for line in text循环处于同一级别。
  • 该语句不合适:只有在定义了和print >> desc时才应该打印。您可以在循环外将它们设置为 None ,并测试它们是否都不是。(或者,您可以在测试中设置和测试)。在这种情况下,打印输出并使用 a来转义循环。Text1Text2for line in textNonehit_count0=1if moldesc[0]hit_count1=1if moldesc[1]hit_count0 and hit_count1break

(所以,用纯代码:)

for f in in_files:
    file = os.path.join(path, f)
    with open(file, "r") as text:
        hit_count = 0
        hit_count1 = 0
        for line in text:
            if moldesc[0] in line:
                Text1 = line.split()[-1]
                hit_count = 1
            if moldesc[1] in line:
                Text2 = line.split()[-1]
                hit_count1 = 1
            if hit_count and hit_count1:
                print >> desc, f + "," + Text1 + "," + Text2
                break

还有第三个问题:

你提到想要之前 的文字Text1?然后你可能想要使用Text1 = line[:line.index(moldesc[0])]而不是你的Text1 = line.split()[-1]......

于 2012-09-25T12:03:40.923 回答
0

我会选择mmap并可能使用 CSV 作为结果文件方法,比如(未经测试)和边缘粗糙......(需要更好的错误处理,可能想要使用 mm.find() 而不是正则表达式,一些代码是从 OP 等逐字复制的……我的电脑电池快没电了……)

import os 
import csv
import mmap
from collections import defaultdict

PATH = r"D:\test"  # note 'r' prefix to escape '\t' interpretation
in_files = os.listdir(path)

fout = open('desc.txt', 'w')
csvout = csv.writer(fout)
csvout.writerow( ['Mol_ID', 'Text1', 'Text2'] )

dd = defaultdict(list)

for filename in in_files: 
    fin = open(os.path.join(path, f))
    mm = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
    # Find stuff
    matches = re.findall(r'(.*?)(Text[12])', mm) # maybe user finditer depending on exact needs
    for text, matched in matches:
        dd[matched].append(text)
    # do something with dd - write output using csvout.writerow()...
    mm.close()
    fin.close()
csvout.close()
于 2012-09-25T12:19:08.590 回答