【发布时间】:2019-08-19 18:03:22
【问题描述】:
我想使用 python 模块 re 快速取消文件中一些不重要的字符串。
我也尝试过其他模块,各种循环和函数,但我能得到的只是找到字符串,而不是用 re.sub 替换它们。
import re
chat = open("chat.txt"
chatText = chat.read()
def deleteMetaData():
for line in chatText:
re.sub("\[\d\d\.\d\d\.\d\d,\s\d\d:\d\d:\d\d\]\sGian\sDogwiler:\s", "", line)
deleteMetaData()
没有错误信息或任何错误信息,什么都没有。我的目标是取消 [20.07.18, 20:23:09] Gian Dogwiler: 在文件的每一行。
【问题讨论】:
-
re.sub返回一个新字符串。你没有使用它,所以它什么都不做 -
请read the docs 看看为什么你不应该忽略
re.sub的返回值。 -
也可以简单的使用字符串替换函数:line.replace(old, new)。见:geeksforgeeks.org/python-string-replace