2014-01-12 44 views
0

可以說我有一個包含如何獲得所有兩個特定單詞之間的詞從一個文本文件,並使用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)) 
+0

該函數返回「標題」(誰,什麼,何時,何處,爲什麼)或計算它們?我在問,因爲在你的例子中,輸出的情況與輸入不同。 – mojo

+0

該函數返回開始(這是示例中的「when」一詞)及其後的所有單詞,直到它到達結尾(這是「爲什麼」 – user3184242

回答

0

這將做你所描述的。我添加了一個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塊完成時,文件會自動關閉。

0
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開頭時爲真,每當行以end開頭時爲False。當該標誌爲True時,該行被打印。

由於帖子中的示例有混合大小寫,我使用方法lower使測試不區分大小寫。

相關問題