[英]How to get all the words between two specific words from a text file and write it in a new text file using python
可以说我有一个包含
Section 1
What: random1
When: random2
Why: random3
Where: random4
How: random5
Section 2
What: dog1
When: dog2
Why: dog3
Where: dog4
How: dog5
Section 3
What: me1
When: me2
Why: me3
Where: me4
How: me5
我想创建一个函数来获取文本文件并查找两个单词,然后在两者之间复制所有内容,并继续收集数据并将其放入新的文本文件中。
例如: def my_function(document, start, end):
在交互窗口中,我将放置my_function("testing.txt, "when", "why")
,它应该创建一个包含数据的新文本文件:
when: random2
when: dog2
when: me2
因此,该函数将获取这两个单词之间的所有数据,并且这两个单词不止一次出现,因此必须不断浏览文件。
不同线程中的用户发布了可能对我有帮助的解决方案,但是我不确定如何将其放入函数中,并且我不理解所使用的代码。
这来自不同的线程 ,解决方案为:falsetru
import itertools
with open('data.txt', 'r') as f, open('result.txt', 'w') as fout:
while True:
it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
if next(it, None) is None: break
fout.writelines(itertools.takewhile(lambda line: line.strip() != 'End', it))
def fn(fname, start, end):
do_print = False
for line in open(fname).readlines():
if line.lower().startswith(start.lower()):
do_print = True
elif line.lower().startswith(end.lower()):
do_print = False
if do_print:
print(line.strip())
产生输出:
>>> fn('testing.txt', 'when', 'why')
When: random2
When: dog2
When: me2
它仅通过逐行浏览文件并在每行以start
时设置标志True以及在每行以end
开头时设置False来工作。 当标志为True时,将打印该行。
由于文章中的示例混合使用大小写,因此我使用lower
的方法使测试不区分大小写。
这将按照您的描述进行。 我添加了dest_path
输入以指定输出文件。
def my_function(source_path, dest_path, start_text, stop_text):
# pre-format start and end to save time in loop (for case insensitive match)
lower_start = start_text.lower()
lower_stop = stop_text.lower()
# safely open input and output files
with open(source_path, 'r') as source, open(dest_path, 'w') as dest:
# this variable controls if we're writing to the destination file or not
writing = False
# go through each line of the source file
for line in source:
# test if it's a starting or ending line
if line.lower().startswith(lower_start): writing = True
elif line.lower().startswith(lower_stop): writing = False
# write line to destination file if needed
if writing: dest.write(line)
请注意, with
块结束时,文件将自动关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.