python 3 : Join lines of file if its not endswith a special character

标签 python python-3.x file

假设一个日志文件格式如下:

TIMESTAMPの[INFO]のevery message ends withの
TIMESTAMPの[INFO]のa message
that contains new-line character
even its still ends withの
TIMESTAMPの[INFO]のevery message ends withの
TIMESTAMPの[ERROR]のanother message
have new-line characters in itの
TIMESTAMPの[ERROR]のevery message ends withの

我怎样才能像这样显示这个文件:

TIMESTAMPの[INFO]のevery message ends withの
TIMESTAMPの[INFO]のa message that contains new-line character even its still ends withの
TIMESTAMPの[INFO]のevery message ends withの
TIMESTAMPの[ERROR]のanother message have new-line characters in itの
TIMESTAMPの[ERROR]のevery message ends withの

最佳答案

只需过滤行,然后使用join

import re
with open('log_file') as file:
    union = ''.join(filter(lambda line: re.match(r'\w+'), file.readlines()))
    # change the regex as per your definition of 'special characters'.

关于 python 3 : Join lines of file if its not endswith a special character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48397272/

相关文章:

python - 检查方法是否导入,from X import Y

一个程序可以同时在同一个 FILE* 上调用 fflush() 吗?

javascript - Python 中的 Webdriver - 执行 JavaScript 文件并将参数传递给其函数

python - 在 Flask 响应头中设置 Unicode 文件名

python - Python 中 "string"的逻辑值是多少?

javascript - for循环中的语法解释?

python - 导入模块的开发版本而不是站 pip 包中安装的版本

python - C++ std::vector 乘法中是否存在已知的不一致行为?

java - 当尝试通过读取文件打印二维数组时,我的输出收到 Null

javascript - 从网页创建 html 文件