2014-02-06 27 views
0

我的目標是將文本文檔分成不同的文本百分比(5%,10%,15%...%),然後將每個文本部分插入位於目錄中的不同文件。如何在python中將文本的不同部分從一個文件傳輸到另一個文件

My attempt 

用於打開和分割文本文檔爲分數的代碼。

def text_percent(fn, *percentages): 
    text = open(fn).read() 
    return [text[:int(pt/100.*len(text))] for pt in percentages] 

vi=range(5,100,5) 

for x in vi: 
    print "\n\n".join(text_percent("C:\zzzz",x)) 

代碼用於打開(在目錄中)轉換成文本的不同部分將被插入

files_=[] 
def dir_files(paf): 
    for dirname, dirnames, filenames in os.walk(paf): 
     for filename in filenames: 
      l=os.path.join(dirname, filename) 
      files_.append(l) 
    return (files_) 

區困難的文件: 如何自動取文本的5%並將其插入目錄的第一個文件,然後將10%插入目錄的第二個文件中,依此類推。

感謝您的建議。

回答

0

代碼的一個問題是您的text_percent函數將文件開頭的所有文本都指定到您指定的百分點,而不僅僅是您想要的部分。下面將打破文件到你想要的片段:

def text_percent(fn, percentages): 
    test = open(fn).read() 
    # convert the percents to the number of characters 
    percentinchars = map(lambda x: int(x * len(text)/100), [0] + percentages + [100]) 
    # convert the markers into pairs of lo/hi bounds 
    bounds = zip(percentinchars, percentinchars[1:]) 
    # use those lo/hi bounds to get the actual character sets 
    return [text[lo:hi] for lo,hi in bounds] 

另一個問題是,你只能通過一個單一的百分之標記的功能,而不是你想要的百分比標記。下面我將百分比標記的全部範圍傳遞給函數,並從文件中獲取完整的分段列表。

print "\n\n".join(text_percent("C:\zzzz", range(5,100,5))) 
相關問題