извлекать имя, адрес электронной почты и номер и сохранять его в переменной - PullRequest
0 голосов
/ 30 марта 2019

Я хочу извлечь имя, адрес электронной почты и номер телефона всех разговоров, а затем сохранить их в различные переменные.Я хочу сохранить его так: a = max, b = email и т. Д.

Это мой текстовый файл:

[11:23] max : Name : max

Email : max@gmail.com

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

Ответы [ 2 ]

1 голос
/ 30 марта 2019

Это совсем не то, что делает split.Возможно, вы путаете его с in.

. В любом случае регулярное выражение будет делать:

import re

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

Email : max@gmail.com

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': 'max@gmail.com',
 '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 голосов
/ 30 марта 2019

Удалите эту строку в вашем коде: "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)
...