2014-01-12 45 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使测试不区分大小写。

相关问题