python - 将文件中的字符串替换为 re

标签 python regex

我想使用 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() 不会自动替换文件中的数据 - 您还需要将其写入文件。 This answer提供了一个很好的例子;我稍微修改了它以匹配您的代码。请注意,您的 chat = open("chat.txt" 行中还缺少右括号。

import re

chat = open("chat.txt")
chatout = open("out.txt", "w")

def deleteMetaData():
  for line in chat:
    chatout.write(re.sub("\[\d\d\.\d\d\.\d\d,\s\d\d:\d\d:\d\d\]\sGian\sDogwiler:\s", "", line))

deleteMetaData()

chat.close()
chatout.close()

使用完文件后,不要忘记 .close() 文件。

Try it here!

关于python - 将文件中的字符串替换为 re,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57561851/

相关文章:

Python 请求模块卡在套接字连接上,但 cURL 有效

用于在 SI 单位前缀之间进行转换的 Python 库

javascript - 使用正则表达式,有条件地替换为 $1 或空字符串

ruby-on-rails - Ruby on Rails 中用于客户端服务器的正则表达式

python从混合代码中选择文本

Python:比较列表和元组列表

Python MySQLdb 处理多个游标 : Command out of sync

python - 从主文件夹的子文件夹中随机提取文件

Python 正则表达式,用于空白行之前的所有内容

c# - 需要正则表达式来关闭或替换引号