[英]Python - deleting variables from text-data using regex
我正在使用蟒蛇。 我想刪除包含用戶可以放入的變量 (input_numb) 的文件行。
input_numb = ['13', '04'] ## These are variable (depending on what the user puts in)
變量只有在一行中沒有其他文本時才應該被刪除。 如果在它之前或之后有一些文本,它們將不會被刪除。 我用下面的正則表達式(行)嘗試了它,但它仍然返回所有 13 和 04。
line = line.replace('\^'+input_numb+'\$', '')
下面是一個數據示例:
13
Some text is good.
The text has 13 lines
13 is a nice number.
13
Some text.
Some more text 04.
04.
Some text.
輸出數據是:
Some text is good.
The text has 13 lines
13 is a nice number.
Some text.
Some more text 04.
Some text.
我建議省略與input_numb
列表項完全匹配的所有行。
編譯以下正則表達式:
rx = re.compile(r'^(?:{})$'.format("|".join(input_numb)))
然后測試每一行是否匹配模式,如果不匹配,則將該行寫入新文件,否則,不執行任何操作:
if not rx.search(line):
fw.write(line) # where fw is the file handle where output is written
在某些情況下, if not rx.search(line.rstrip()):
,您可能希望從尾隨空格中if not rx.search(line.rstrip()):
該行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.