我寫一個腳本提取從文件數據和分割數據到多個文件的內容爲每個文件由5分裂「@」 S提取文本使用python
實施例:
@@@@@
hello
@@@@@
world
@@@@@
在這種情況下
,「你好」應該是在一個文件和「世界」應在另一個文件
我使用python
我寫一個腳本提取從文件數據和分割數據到多個文件的內容爲每個文件由5分裂「@」 S提取文本使用python
實施例:
@@@@@
hello
@@@@@
world
@@@@@
在這種情況下
,「你好」應該是在一個文件和「世界」應在另一個文件
我使用python
文件如果我正確理解你的要求,你要能夠把輸入從一個文件的分隔符@@@@@
@@@@@
hello
@@@@@
world
@@@@@
,這將產生用於每一個塊之間的文件
hello
和
world
您可以使用re.split獲得劈叉
splits = re.split("[@]{5}\n", input_buffer)
會看到這樣的(注:以上數據假設分裂還包括換行符)
['', 'hello\n', 'world\n', '']
和以僅獲得具有實際文本的分割(假定要刪除尾隨的新行)
[i.strip() for i in splits if i]
輸出文件名也未指定,以便使用
for index, val in enumerate([i.strip() for i in splits if i]):
with open("output%d"%index, "w+") as f:
創建一個名爲OUTPUT0文件,outputN
import re
import StringIO
input_text = '''@@@@@
hello
@@@@@
world
@@@@@
'''
string_file = StringIO.StringIO(input_text)
input_buffer = string_file.read()
splits = re.split("[@]{5}\n", input_buffer)
for index, val in enumerate([i.strip() for i in splits if i]):
with open("output%d"%index, "w+") as f:
f.write(val)
只是一個幫手,能顯着使用不同的正則表達式來拆分上,改變輸出名稱更適合的東西等
此外,如果作爲這個問題的標題說[ - 和 - ]拆分之間的文本可以獲得使用re.findall而不是
input_text = '''[-hello-]
[-world-]
'''
string_file = StringIO.StringIO(input_text)
input_buffer = string_file.read()
splits = re.findall("\[-(.*)-\]", input_buffer)
for index, val in enumerate(splits):
with open("output%d"%index, "w+") as f:
f.write(val)
很確定'[@] {5} \ n'不匹配最後的'@@@@@'。也許更好:'[@] {5} \ n?'或者完全刪除換行符並讓'strip()'完成工作。 – brianpck
@brianpck是正確的,我假設換行符被終止的文件, –
這可能做的伎倆:
with open('a.txt') as r: #open source file and assign it to variable r
r = r.read().split('@@@@@') #read the contents and break it into list of elements separated by '@@@@@'
new = [item.strip() for item in r if item] #clean empty rows from the list
for i, item in enumerate(new): #iterate trough new list and assign a number to each iteration starting with 0 (default)
with open('a%s.txt' % i+1, 'w') as w: #create new file for each element from the list that will be named 'a' + 'value of i + 1' + '.txt'
w.write(item) #writing contents of current element into file
這將閱讀您的文件,我叫「A.TXT」和生成名爲a1.txt, a2.txt ... an.txt
你能解釋一下我的工作原理嗎? –
@nijeeshjoshy我爲每一行添加了評論。希望它清除圖片。 – zipa
告訴我們您現在的代碼請 – Ivaro18
該程序的哪一部分是您遇到問題? – JohnnyWineShirt