python - 如何将re.findall应用于文件为空列表

标签 python regex list

我在下面有文本文件:

Is there any way to do removing the empty list while using re.findall

Started : Sunday, May 1, 2016 1:59:16 PM
Source : C:\RegularExpressionsWithDotNet\robocopytest\source\தமிழ்\हिन्दी\English
Dest : C:\RegularExpressionsWithDotNet\robocopytest\destn\
Started : Sunday, May 1, 2016 1:59:16 PM
Source : C:\RegularExpressionsWithDotNet\robocopytest\source\தமிழ்\हिन्दी\English
Dest : C:\RegularExpressionsWithDotNet\robocopytest\destn\


我的代码如下:

with open(r'C:\debug.log', 'r', encoding='utf-8') as fr:
    eachline = fr.read()
data = [eachline.strip() for eachline in eachline.splitlines()]
datalinelist = []
for i in data:
    datalinelist.append(re.findall(r'\bSource : (.+)', i))
datalinelist


我的出门是[[], ['C:\\RegularExpressionsWithDotNet\\robocopytest\\source\\தமிழ்\\हिन्दी\\English'], [], [], ['C:\\RegularExpressionsWithDotNet\\robocopytest\\source\\தமிழ்\\हिन्दी\\English'], []]

有什么办法可以在使用re.findall时删除空列表

如果我在做[line for line in open(file,'r',encoding='utf-8') if re.findall(r'Source : .+',line)]

我得到了正确的['Source : C:\\RegularExpressionsWithDotNet\\robocopytest\\source\\தமிழ்\\हिन्दी\\English\n', 'Source : C:\\RegularExpressionsWithDotNet\\robocopytest\\source\\தமிழ்\\हिन्दी\\English\n']

处理with条件时有什么错误

最佳答案

with open(r'debug.log', 'r', encoding='utf-8') as fr:
    eachline = fr.read()
data = [eachline.strip() for eachline in eachline.splitlines()]
datalinelist = []
for i in data:
    datalinelist.extend(re.findall(r'\bSource : (.+)', i))
datalinelist


['C:\ RegularExpressionsWithDotNet \ robocopytest \ source \ ????? \ ?????? \ English',
'C:\ RegularExpressionsWithDotNet \ robocopytest \ source \ ????? \ ?????? \ English']

关于python - 如何将re.findall应用于文件为空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58787342/

相关文章:

python - 在 python 中查找 List 长度的 O(1) 背后的原因

javascript - 替换数字模式中的子字符串

Python:有没有办法将一串数字分成每第三个数字?

python - 将平均值保存在文本文件中

列表上的 Python 分配属性

regex - RE 到 NFA Thompson 的构造步骤 ((c|a)b*)*

javascript - 捕获 url 的第一部分

python - 如何根据字典值中的顺序将字典转换为列表

Python:AttributeError:Response.read 和 .text 不起作用

python - 组合总和python递归范围