繁体   English   中英

如何在 Python 中的文本文件中提取部分图案线条的一部分?

[英]How to extract parts of a partially patterned line in a text file in Python?

我有一个包含以下内容的文本文件:

0:00 txt txt e-mail1_to_extract txt_to_extract1 txt txt /data
0:00 txt txt e-mail2_to_extract txt_to_extract2 txt txt /data
0:00 txt txt txt e-mail3_to_extract txt_to_extract3 txt txt /var
0:00 txt txt txt txt e-mail4_to_extract txt_to_extract4 txt txt /var
0:00 txt txt e-mail5_to_extract txt_to_extract5 txt txt /data

首先,我想提取“0:00”和“/data”或“/var”之间的所有这些行。 其次,我想处理这些数据,以便我只能提取其中的两部分。 这个已经提取的范围中包含的文本不是标准化的,所以我不能使用“startwith”/“endwith”之类的东西,但是,整个文本被连接起来(就像一个完整的单词)并且它的位置总是在电子邮件之后重复部分。 有什么方法可以专门映射该部分并提取电子邮件+下一个字符串?

Txt = 我不想提取的额外文本。

我已经尝试从下面的代码开始,但没有得到任何结果:

with open('content.txt') as infile, open('extraction.txt', 'w') as outfile:
copy = False
for line in infile:
    if line.strip() == "0:00":
        copy = True
        continue
    elif line.strip() == "/":
        copy = False
        continue
    elif copy:
        outfile.write(line)

期望的输出:

e-mail1_to_extract txt_to_extract1
e-mail2_to_extract txt_to_extract2
e-mail3_to_extract txt_to_extract3
e-mail4_to_extract txt_to_extract4
e-mail5_to_extract txt_to_extract5

谢谢!

我使用了您提供的格式的示例文件 -

0:00 txt txt123 abc@abs.com txt_to_extract1 txt6456 txtssss /data
0:00 txt11 txt111 abd@rtx.vg txt_to_extract2 txtssss txtffff /data
0:00 txt111 txt123 txt tyrr@rgahb.com txt_to_extract3 txtosvbsvs txtkkkk /var
0:00 txt456 txt3663 srsr31415s@gagha.gha txt e-mail4_to_extract txt_to_extract4 txabjahsjat txtasba /var
0:00 txtGJK txtfggg gfa456vaj@aghaha.com txt_to_extract5 txtbxajla txtzbaza /data

我使用了以下代码(用于确定电子邮件的功能,请相应地更改正则表达式)-

import re 
  
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
def check(email):    
    if(re.search(regex,email)):  
        return True
    else:  
        return False
        
def getcols(row):
    for i in row.keys():
        if check(row[i]):
            return str(row[i]) + " " + str(row[i+1])
        else:
            return ""


ls = []
with open('TestData.txt') as infile, open('extraction.txt', 'w') as outfile:
    for line in infile:
        ls = line.split()
        for i in range(len(ls)):
            if check(ls[i]):
                try:
                    outfile.write(ls[i] + " " + ls[i+1]+"\n")
                except:
                    pass
                
            

我得到以下输出 -

abc@abs.com txt_to_extract1
abd@rtx.vg txt_to_extract2
tyrr@rgahb.com txt_to_extract3
srsr31415s@gagha.gha txt
gfa456vaj@aghaha.com txt_to_extract5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM