簡體   English   中英

從文本文件python中刪除特定字符串(不是行)

[英]Delete a specific string (not line) from a text file python

我有一個文本文件中有兩行文本文件:

<BLAHBLAH>483920349<FOOFOO>
<BLAHBLAH>4493<FOOFOO>

這是文本文件中唯一的東西。 使用python,我想寫入文本文件,以便我可以從每一行中帶走BLAHBLAH和FOOFOO。 這似乎是一個簡單的任務,但刷新我的文件操作后,我似乎無法找到一種方法來做到這一點。 非常感謝幫助:)

謝謝!

如果它是你說的文本文件,而不是HTML / XML /其他東西,只需使用replace

for line in infile.readlines():
    cleaned_line = line.replace("BLAHBLAH","")
    cleaned_line = cleaned_line.replace("FOOFOO","")

並將cleaned_line寫入輸出文件。

f = open(path_to_file, "w+")

f.write(f.read().replace("<BLAHBLAH>","").replace("<FOOFOO>",""))
f.close()

更新(保存到另一個文件):

f = open(path_to_input_file, "r")
output = open(path_to_output_file, "w")

output.write(f.read().replace("<BLAHBLAH>","").replace("<FOOFOO>",""))
f.close()
output.close()

考慮正則表達式模塊 re。

result_text = re.sub('<(.|\n)*?>',replacement_text,source_text)

<>中的字符串被識別。 它是非貪婪的,即它將接受最小可能長度的子串。 例如,如果你有“<1> text <2> more text” ,貪婪的解析器會接受“<1> text <2>” ,但非貪婪的解析器會接受“<1>”“<2 >“

當然,您的replacement_text將是'',source_text將是文件中的每一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM