python - Python:如何在文本文件中查找关键字,在该关键字左侧保存 60 个字符,循环直到文本文件结尾
问题描述
定义两个关键字后,我的目标是:
读取非结构化文本文件的全部内容(超过 1000 行文本)
循环遍历内容,每次点击关键字时获取关键字左侧的 60 个字符
将每个 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()
我需要有关此代码中间部分的帮助。例如,如果源文本文件显示:
“一些文字,一些文字,一些文字,关键字”
我想返回:
“一些文字,一些文字,一些文字,”
在找到的每个关键字的新行中。
谢谢你。
解决方案
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])
推荐阅读
- php - 无法在 slim3 php 中创建新路由
- amazon-web-services - AES 256 加密和解密
- java - 如何保存 EMF 模型
- sql - 如何修复相关子查询错误选择的数据?
- javascript - Uncaught (in promise) SyntaxError: Unexpected end of JSON input in chrome extension
- java - 这两个递归实现是否查找二叉树是否等效?
- asp.net - mvc.net core 2.2 中经过身份验证的用户的默认起始页>
- powershell - 用于从所有子文件夹中删除超过 30 天的文件的 PowerShell 脚本
- laravel - 在指向子域的同一服务器上使用 docker 运行两个 Laravel 应用程序
- reactjs - 为什么嵌套 package.json 存在时 webpack 无法编译