如何使用python在文本文件中查找特定的文本行?

时间:2016-03-14 05:05:33

标签: python regex python-3.x python-3.5 pdf-scraping

def match_text(raw_data_file, concentration):
    file = open(raw_data_file, 'r')
    lines = ""
    print("Testing")
    for num, line in enumerate(file.readlines(), 0):
        w = ' WITH A CONCENTRATION IN ' + concentration
        if re.search(w, line):
            for i in range(0, 6):
                lines += linecache.getline(raw_data_file, num+1)
                try:
                    write(lines, "lines.txt")
                    print("Lines Data Created...")
                except:
                    print("Could not print Line Data")
        else:
            print("Didn't Work")

我正在尝试打开.txt文件并搜索特定字符串。

2 个答案:

答案 0 :(得分:0)

如果您只是尝试将包含字符串的所有行写入文件,则可以这样做。

def match_text(raw_data_file, concentration):
    look_for = ' WITH A CONCENTRATION IN ' + concentration
    with open(raw_data_file) as fin, open('lines.txt', 'w') as fout:
        fout.writelines(line for line in fin if look_for in line)

答案 1 :(得分:0)

修正了我自己的问题。以下内容适用于查找特定行并获取匹配行后面的行。

def match_text(raw_data_file, match_this_text):
    w = match_this_text
    lines = ""
    with open(raw_data_file, 'r') as inF:
        for line in inF:
            if w in line:
                lines += line //Will add the matched text to the lines string
                for i in range(0, however_many_lines_after_matched_text):
                    lines += next(inF)
                //do something with 'lines', which is final multiline text

这将返回多行以及用户想要的匹配字符串。如果问题令人困惑,我道歉。