[英]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.