提取名称,电子邮件和号码并将其保存到变量中

问题描述 投票:-1回答:2

我想提取所有会话的名称,电子邮件和电话号码,然后将它们保存到不同的变量中。我想这样保存:a = max,b = email等等。

这是我的文本文件:

[11:23] max : Name : max

Email : [email protected]

Phone : 01716345678

[11:24] harvey : hello there how can i help you
[11:24] max : can you tell me about the latest feature

这是我的代码。我在这里错过了什么?

in_file = open("chat.txt", "rt")

contents = in_file.read()
#line: str
for line in in_file:
    if line.split('Name :'):
        a=line
        print(line)

    elif line.split('Email :'):
        b = line

    elif line.split('Phone :'):
        c = line


    else:
        d = line
python parsing extract
2个回答
1
投票

这根本不是split所做的。你可能会把它与in混淆。

无论如何,正则表达式将:

import re

string = '''[11:23] max : Name : max

Email : [email protected]

Phone : 01716345678

[11:24] harvey : hello there how can i help you
[11:24] max : can you tell me about the latest feature'''

keys = ['Name', 'Email', 'Phone', 'Text']
result = re.search('.+Name : (\w+).+Email : ([\w@\.]+).+Phone : (\d+)(.+)', string, flags=re.DOTALL).groups()

{key: data for key, data in zip(keys, result)}

输出:

{'Name': 'max',
 'Email': '[email protected]',
 'Phone': '01716345678',
 'Text': '\n\n[11:24] harvey : hello there how can i help you\n[11:24] max : can you tell me about the latest feature'}

0
投票

在代码中删除此行:“contents = in_file.read()”

另外,使用“in”而不是“split”:

in_file = open("chat.txt", "rt")
for line in in_file:
    if ('Name') in line:
        a=line
        print(a)
    elif 'Email' in line:
        b = line
        print(b)
    elif 'Phone' in line:
        c = line
        print(c)
    else:
        d = line
        print(d)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.