用Python阅读列表

用Python阅读列表,python,Python,嘿,我正在尝试读取两个txt文件。一个是列表,另一个是主文件。当列表中的一个单词与主文件中的一个单词匹配时,我想打印该单词所在的行、匹配单词前的行和匹配单词后的行。以下是当前代码。我似乎只知道如何打印后的行 import os os.chdir(r"XXXX DF") def createlist(): items = [] with open('phrases.txt') as input: for line in input:

嘿,我正在尝试读取两个txt文件。一个是列表,另一个是主文件。当列表中的一个单词与主文件中的一个单词匹配时,我想打印该单词所在的行、匹配单词前的行和匹配单词后的行。以下是当前代码。我似乎只知道如何打印后的行

import os 
os.chdir(r"XXXX DF")
def createlist():
    items = []
    with open('phrases.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist())
# store the list
word_list = createlist()

with open('January 19.txt', 'r') as f:
    for line in f:
    # split the file content to words (first to lines, then each line to it's words)
     for word in line.strip().split():
        # check if each word is in the list
        if word in word_list:
            # do something with word
            print (word, end= '')
            #Print next line 
            print(next(f))
            #Print next line 
        else:
            StopIteration 

你必须记住每一行,以防下一行匹配

prev = None
for line in f:
    # split the file content to words (first to lines, then each line to it's words)
    for word in line.strip().split():
        # check if each word is in the list
        if word in word_list:
            # Print the previous line, matching word, and next line
            print(prev)
            print(word, end= '')
            print(next(f))
    prev = line   # Remember the current line in case of a later match

如果匹配的单词在连续的行中,则此操作不起作用。 还要注意,您的行迭代是不一致的:您“神奇地”在循环中获得了一个额外的行。处理此问题的一种更通用的方法是保留一个行缓冲区,并检查中间的行是否有匹配的字:

buffer = [None, None, next(f)]  Put the first line into the buffer
for line in f:
    buffer = buffer[1:] + [line]   # shift the buffer; add next line
    # Check the buffer's middle line for a match
    # split the file content to words (first to lines, then each line to it's words)
    for word in buffer[1].strip().split():
        # check if each word is in the list
        if word in word_list:
            # Print the matching line and adjacent lines
            print(buffer)
            break
您仍然有一两个特殊情况需要测试和检查;我把它留给学生做练习。但是,它更灵活