可以說我有一個包含如何獲得所有兩個特定單詞之間的詞從一個文本文件,並使用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
那麼該功能將所有這兩個詞和這兩個詞之間的數據出現不止一次,所以它將不得不繼續瀏覽文件。
不同線程中的用戶發佈了一個可以幫助我的解決方案,但我不確定如何將它放入函數中,但我不理解所用的代碼。
這是從different thread,通過解決方案: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))
該函數返回「標題」(誰,什麼,何時,何處,爲什麼)或計算它們?我在問,因爲在你的例子中,輸出的情況與輸入不同。 – mojo
該函數返回開始(這是示例中的「when」一詞)及其後的所有單詞,直到它到達結尾(這是「爲什麼」 – user3184242