[英]how to delete all lines containing Letters and characters for a textfile
我有一個包含單詞、數字和字符的文本文件。 我想刪除所有帶有字符和單詞的行,並保留帶有數字的行。 我發現所有帶有單詞和字符的行都有字母“r”。 所以我把我的代碼寫成:
文本文件包含這些行作為示例:
-- for example
-- 7 Febraury 2022
5 7 1 5 3.0 2
3*2 3 5 7.0 3
您只能使用
regex<\/code>找到單詞
import re
with open(r'text_file.txt', 'r') as f:
data = f.readlines()
with open(r'text_file.txt', 'w') as f:
for line in data:
if re.findall(r"(?!^\d+$)^.+$", line):
f.write(line)
如果您想在不導入任何內容(例如重新)的情況下執行此操作,那么您可以這樣做:
keep_these = []
with open('test.txt', encoding='utf-8') as infile:
for line in infile:
if all(t.replace('*', '0').isdigit() for t in line.strip().split()):
keep_these.append(line)
print(keep_these)
您可以使用正則表達式庫
re<\/code> 。
一種方法是循環遍歷這些行,然后僅當
re.match("[^0-9 ]", line) == None<\/code>時才保留該行。
"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.