![](/img/trans.png)
[英]Repeatedly extract text between two delimiters with a variable in a text file in Python
[英]Extract text between two delimiters from a text file
我目前正在寫有關CEO自戀的碩士論文。 為了對其進行衡量,我必須進行收入電話文本分析。 我按照此鏈接中可用的答案用python寫了一個代碼,該代碼使我可以從收入通話記錄中提取“問題與答案”部分。 該文件是這樣的(它稱為“ testoestratto.txt”):
..............................
Delimiter [1]
..............................
A text that I don't need
..............................
Delimiter CEO [2]
..............................
I need this text
..............................
Delimiter [3]
..............................
[...]
..............................
Delimiter CEO [n-1]
..............................
I also need this text
..............................
Delimiter [n]
..............................
我還有另一個txt文件(“ lista.txt”),在其中我從筆錄中提取了所有定界符:
Delimiter [1]
Delimiter CEO [2]
Delimiter [3]
[...]
Delimiter CEO [n-1]
Delimiter [n]
我想做的是從Detester CEO [2]和Delimiter [3],...之間以及Delimiter CEO [n-1]和Delimiter [n]之間的“ testoestratto.txt”中提取文本。 提取的文本必須寫在“ test.txt”中。 因此,如果“ lista.txt”中的分隔符包含CEO一詞,則我需要“ testoestratto.txt”中的文本,該文本位於該特定分隔符和“ lista.txt”中下一個不包含“首席執行官”。 為了做到這一點,我編寫了以下代碼:
with open('testoestratto.txt','r', encoding='UTF-8') as infile, open('test.txt','a', encoding='UTF-8') as outfile, open('lista.txt', 'r', encoding='UTF-8') as mylist:
text= mylist.readlines()
text= [frase.strip('\n') for frase in text]
bucket=[]
copy = False
for i in range(len(text)):
for line in infile:
if line.strip()==text[i] and text[i].count('CEO')!=0 and text[i].count('CEO')!= -1:
copy=True
elif line.strip()== text[i+1] and text[i+1].count('CEO')==0 or text[i+1].count('CEO')==-1:
for strings in bucket:
outfile.write(strings + '\n')
elif copy:
bucket.append(line.strip())
但是,“ test.txt”文件為空。 你可以幫幫我嗎?
PS:我是python的初學者,所以如果代碼混亂,我要道歉
您需要在代碼中進行一些更改。
首先,這里的關鍵是在每次讀取一次該文件之后將其重置為文件的開頭。 由於尚未執行此操作,因此在嵌套for循環的第一次迭代之后,您的代碼從不從頭開始讀取文件。 您可以使用infile.seek(0)
進行此操作。
其次,一旦寫入文件,就需要將標志“ copy”的值重置為False。 這樣可以確保您不會將不需要的文本寫到文件中。 此外,您還需要清空存儲區,以避免在輸出中多次寫入相同的行。
第三,您在elif
語句中包含了許多不必要的字符串檢查。
我在以下代碼中進行了更改:
with open('testoestratto.txt','r', encoding='UTF-8') as infile,
open('test.txt','a', encoding='UTF-8') as outfile, open('lista.txt', 'r',
encoding='UTF-8') as mylist:
text= mylist.readlines()
text= [frase.strip('\n') for frase in text]
bucket=[]
copy = False
for i in range(len(text)):
for line in infile:
if line.strip('\n')==text[i] and text[i].count('CEO') > 0:
copy=True
elif copy and line.strip('\n') == text[i+1]:
for strings in bucket:
outfile.write(strings + '\n')
copy = False
bucket = list()
elif copy:
bucket.append(line.strip())
infile.seek(0)
話雖如此,您也可以優化代碼。 如您所見,此代碼在O(n ^ 3)中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.