我有以下导出的文本文件:
14:00:01 type1 "xyz" has no relationships... ಠ_ಠ
14:00:01 type2 "xyza" has no relationships... ಠ_ಠ
14:00:01 type2 "aaaa" has no relationships... ಠ_ಠ
14:00:01 type3 "asdg" has no relationships... ಠ_ಠ
14:00:01 type4 "dhj" has no relationships... ಠ_ಠ
我正在尝试找到一种方法来从此文件中检索两个信息
- 类型(在本例中为时间之后、双引号内之前的元素)
- 双引号内的内容
预期输出:
type1 xyz
type2 xyza
type2 aaaa
type3 asdg
type4 dhj
使用我当前的代码,我可以获取双引号内的内容,但我不知道如何获取类型并将其与我的正则表达式合并:
import os, yaml
import argparse
import re
with open('stackoverflow.txt') as f:
content = f.readlines()
matches=re.findall(r'\"(.+?)\"',str(content))#get the content within the double quote
for x in matches:
print(x)
当前输出:
xyz
xyza
aaaa
asdg
dhj
最佳答案
如果您的 txt 文件始终具有该结构,我会简单地这样做:
with open('stackoverflow.txt') as f:
matches = [' '.join(line.split(' ')[1:3]) for line in f.readlines()]
for x in matches:
print(x)
输出:
type1 "xyz"
type2 "xyza"
type2 "aaaa"
type3 "asdg"
type4 "dhj"
关于python-3.x - 两个正则表达式的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67003852/