Python 如何删除文件中每行的一部分?

Python 如何删除文件中每行的一部分?,python,python-2.7,Python,Python 2.7,我试图打印一些日志文件,但我想消除日志文件中每行的第一部分。 例如: [2018-07-10 15:04:11]用户输入“你好” [2018-07-10 15:04:12]系统响应:“你好!今天过得怎么样?” [2018-07-10 15:04:42]用户输入“我做得很好,谢谢” [2018-07-10 15:04:42]系统响应:“很高兴知道” 我只是想知道 用户输入“hello” 系统响应:“你好!今天过得怎么样?” 用户输入“我做得很好,谢谢” 系统响应:“很高兴知道” 当前代码: i

我试图打印一些日志文件,但我想消除日志文件中每行的第一部分。 例如:

[2018-07-10 15:04:11]用户输入“你好”
[2018-07-10 15:04:12]系统响应:“你好!今天过得怎么样?”
[2018-07-10 15:04:42]用户输入“我做得很好,谢谢”
[2018-07-10 15:04:42]系统响应:“很高兴知道”
我只是想知道

用户输入“hello”
系统响应:“你好!今天过得怎么样?”
用户输入“我做得很好,谢谢”
系统响应:“很高兴知道”
当前代码:

import os
location = '/Users/user 1/Desktop/'

f = open(os.path.join(location, 'xvp.log'), "r")

print(f.read())

您可以尝试
re
模块:

s = '''[2018-07-10 15:04:11] USER INPUT "hello"
[2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today"
[2018-07-10 15:04:42] USER INPUT "I am doing good thank you"
[2018-07-10 15:04:42] SYSTEM RESPONSE: "Good to know"'''

import re

print(re.sub(r'\[(.*?)\]\s+', '', s))
印刷品:

USER INPUT "hello"
SYSTEM RESPONSE: "Hello! How are you doing today"
USER INPUT "I am doing good thank you"
SYSTEM RESPONSE: "Good to know"
要将其连接到代码,只需将字符串从文件读取到变量,然后使用
re.sub
函数。

这是一个开始

import os
location = '/Users/user 1/Desktop/'

f = open(os.path.join(location, 'xvp.log'), "w+")

for line in f.readlines():
    index_ = line.index(']') + 2
    new_line = line[index_:]
    # TODO: save the new_line to the file

f.close()

我的正则表达式不太好,所以很受欢迎。您可以通过使用正则表达式来解决这个问题-

^[[]\d{4}[-]\d{2}[-]\d{2}[ ]\d{2}[:]\d{2}[:]\d{2}[]][ ]
为什么我要使用
^
?所以它开始从字符串的开始匹配,并且在字符串的中间不匹配<代码> [< /代码>,然后匹配整个模式。现在你可以使用Python的代码> Re>/Cult>模块,如-< /P>
import re
catcher = u'^[[]\d{4}[-]\d{2}[-]\d{2}[ ]\d{2}[:]\d{2}[:]\d{2}[]][ ]'
your_string = '[2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today"'
your_string = re.sub(catcher, '', your_string)
# re.sub will replace all the matches
# It takes - (regex_pattern, replace_the_matches_with, your_match_string) 

输出-
系统响应:“您好!今天过得怎么样”

您已经有了哪些代码?编辑了我的代码!