首页 > 解决方案 > Python:如何在文本文件中查找关键字,在该关键字左侧保存 60 个字符,循环直到文本文件结尾

问题描述

定义两个关键字后,我的目标是:

  1. 读取非结构化文本文件的全部内容(超过 1000 行文本)

  2. 循环遍历内容,每次点击关键字时获取关键字左侧的 60 个字符

  3. 将每个 60 个字符的字符串附加到新文本文件的单独行中

我有读取非结构化文本文件并写入新文本文件的代码。

我无法创建将查找每个关键字、获取内容然后循环遍历文件末尾的代码。

很简单,这是我到目前为止所拥有的:

#read file, store in variable
content=open("demofile.txt", "r")

#seek "KW1" or "KW2", take 60 characters to the left, append to text file, loop

#open a text file, write variable contents, close file
file=open("output.txt","w")
file.writelines(content)
file.close()

我需要有关此代码中间部分的帮助。例如,如果源文本文件显示:

“一些文字,一些文字,一些文字,关键字”

我想返回:

“一些文字,一些文字,一些文字,”

在找到的每个关键字的新行中。

谢谢你。

标签: python

解决方案


result = []

# Open the file
with open('your_file') as f:
    # Iterate through lines
    for line in f.readlines():
        # Find the start of the word
        index = line.find('your_word')
        # If the word is inside the line
        if index != -1:
            if index < 60:
                result.append(line[:index])
            else:
                result.append(line[index-60:index])

之后,您可以写入result文件


如果你有几个单词,你可以像这样修改你的代码:

words = ['waka1', 'waka2', 'waka3']

result = []

# Open the file
with open('your_file') as f:
    # Iterate through lines
    for line in f.readlines():
        for word in words:
            # Find the start of the word
            index = line.find(word)
            # If the word is inside the line
            if index != -1:
                if index < 60:
                    result.append(line[:index])
                else:
                    result.append(line[index-60:index])

推荐阅读