我想提取姓名,电子邮件,电话号码和电话号码之后的所有对话,然后将其保存到不同的变量中。我想要将其保存为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
答案 0 :(得分:0)
这根本不是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'}
答案 1 :(得分:0)
在代码中删除此行: “内容= 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)