【问题标题】:How to extract parts of a partially patterned line in a text file in Python?如何在 Python 的文本文件中提取部分图案线的一部分?
【发布时间】:2020-12-14 18:24:57
【问题描述】:

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

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 开始该行,路径结束它。
  • 请为您提供的示例提供所需的输出,以便我们提供更好的帮助。谢谢
  • 完成了,伊桑! :D

标签: python file text extract


【解决方案1】:

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

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

【讨论】:

  • @ronphan 如果答案适合您,请接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2020-12-17
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多