我想在 python 3 中制作一個程式來執行以下操作,但我不確定如何。基本上我想要一個 python 3 腳本,它讀取一個 txt 檔案并在每個文本行中查找某個短語(例如:示例短語)。然后,如果它對帶有匹配短語的一行進行了罰款,它將從其下方的兩行中復制文本并將它們與“:”組合起來,并將其保存到一個新的 txt 檔案中。
例子:
Example Phrase
Text Line One
Text Line Two
Text Line One:Text Line Two
如果有人能幫我做這個,那就太棒了!
提前感謝所有幫助,SpaceBurn
編輯:我想提一下示例短語不會是文本行中的唯一內容(例如:這是一些示例短語文本)。如果程式在其中看到一行帶有“Example Phrase”,則會復制其下方的兩行并將其與前面提到的“:”組合起來。
uj5u.com熱心網友回復:
您可以使用find()method 并遍歷從檔案中讀取的行。當您到達帶有短語的行時,收集該行的索引并中斷回圈。然后,用join()方法加入行,不要忘記從行開始,line_id 1以收集與您的短語行之后的行。
text_lines = open("my_file.txt", "r").readlines()
for i_, line in enumerate(lines):
if line.find("my_phrase")!=-1:
line_id = i_
break
joined_lines = ":".join(lines[line_id 1:)
out_file = open("my_output.txt", "w")
out_file.write(joined_lines)
當心。這將在輸出檔案中創建一個只有一行的檔案。不知道你以后想用這些做什么。
uj5u.com熱心網友回復:
您可以使用正則運算式來匹配您的模式并加入下一行:
import re
pattern = 'Example Phrase'
regex = pattern '[^\n]*\n([^\n]*)\n([^\n]*)\n?'
with open('input.txt', 'r') as a, open('output.txt', 'w') as b:
for m in re.finditer(regex, a.read()):
b.write(':'.join(m.groups()) '\n')
注意。我在手機上打字,無法測驗代碼。
uj5u.com熱心網友回復:
這種方法可以使用大輸入檔案,因為它會從輸入檔案中逐行讀取,記錄要搜索的文本并處理其下方的文本行。它還可以處理要搜索的連續文本。代碼中包含輕注釋。
代碼
def mysearcher(infn, outfn, text_search):
"""
Read infn file and find text_search, if found write the the 2 lines below it, to outfn file.
"""
found = 0 # counter if text_search is found
ret = [] # temp storage
with open(outfn, 'w') as w: # open file for writing overwrite mode
with open(infn, 'r') as f: # open file for reading
for lines in f:
line = lines.rstrip()
if found:
ret.append(line) # add new line in the ret list
# Write to output if ret list has two elements.
if len(ret) == 2:
w.write(f'{ret[0]}:{ret[1]}\n') # write to output
# Update ret and found counter.
found -= 1
if found == 0:
ret = [] # reset
else:
# Don't reset ret, there is successive text_search found.
ret.pop(0) # just remove the first element
if text_search in line:
found = 1
# Start
infn = 'input.txt'
outfn = 'out.txt'
text_search = 'Example Phrase'
mysearcher(infn, outfn, text_search)
示例輸入檔案文本內容
輸入.txt
Example Phrase
Text Line One
Text Line Two
New Example Phrase
Example Phrase
Example Phrase I did
Text Line Three
Text Line Four
輸出
輸出.txt
Text Line One:Text Line Two
Example Phrase:Example Phrase I did
Example Phrase I did:Text Line Three
Text Line Three:Text Line Four
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388184.html
