【问题标题】:Printing the next line after a word matches between two TXT files在两个 TXT 文件之间的单词匹配后打印下一行
【发布时间】:2021-01-18 16:22:23
【问题描述】:

我能够在创建列表并与 txt 文件进行比较时找到已经存在的堆栈溢出代码,这非常棒。但是,一旦我尝试使用 (next (f), end "")print(''.join(islice(f, 3))) 尝试匹配单词,我也想打印 txt 文件中的下一行,但我无法得到我想要的结果。

下面是代码。我再一次不相信代码,它来自这个原始的堆栈溢出帖子How to search a text file for a specific word in Python

import os

os.chdir(r"xx")

def createlist():
    items = []
    with open('phrases.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist())
word_list = createlist()

with open('text.txt') as f
    for word in (sum([x.split() for x in f.read().split('\n')], [])):
        if word in word_list:
            print (word)
        else:
            StopIteration

【问题讨论】:

  • 顺便说一句,在脚本中硬编码os.chdir() 会降低其有用性。只需让它在当前目录中搜索两个文件,或者接受两个文件名作为命令行参数,这样您就可以在任意两个目录中的任意两个文件上运行它。

标签: python


【解决方案1】:
with open('text.txt', 'r') as f:
    for line in f:
        for word in line.strip().split():
            if word in word_list:
                print (word)
                print (next(f))
            else:
                StopIteration

要显示以msg 打开的文件的下一行,请在for line in msg: 循环中使用next(msg)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-12
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多