python - 嗨,试图从文本文件中提取名称 + 电子邮件,但不知道如何将输出彼此相邻
问题描述
我试图让我的数据并排输出,姓名和电子邮件。现在它只打印电子邮件,然后打印姓名。
这是我的代码:
import re
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
inputfile = open('/Users/jchome/Downloads/StockXRF/untitled.txt','r')
string = inputfile.read()
def extract_email_addresses(string):
r = re.compile(r'[\w\.-]+@[\w\.-]+')
return r.findall(string)
def ie_preprocess(document):
document = ' '.join([i for i in document.split() if i not in stop])
sentences = nltk.sent_tokenize(document)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
def extract_names(document):
names = []
sentences = ie_preprocess(document)
for tagged_sentence in sentences:
for chunk in nltk.ne_chunk(tagged_sentence):
if type(chunk) == nltk.tree.Tree:
if chunk.label() == 'PERSON':
names.append(' '.join([c[0] for c in chunk]))
return names
if __name__ == '__main__':
emails = extract_email_addresses(string)
names = extract_names(string)
print (emails + names)
输出:
['1lawrencenage1l@gmail.com', george@gmail.com, 'Lawrence', 'George']
如何将输出彼此相邻并写入文本文件?
解决方案
您可以执行以下操作:
import pandas as pd
zipped = list(zip(emails, names))
df = pd.DataFrame(zipped, columns = ['emails' , 'names'])
在此之后,您可以打印数据框,并且可以使用例如to_csv方法将输出保存到文件中。
推荐阅读
- javascript - 填充 selectize.js 字段而不触发 item_add 事件
- postgresql - 如何在 ecto 查询中加入多个模型 Ecto
- android - expo + react-native:发送日志消息时出现问题
- ios - Lauchscreen.storyboard 风景闪屏
- linux - 用没有sed的shell替换二进制文件中的十六进制
- mysql - mysql/mariadb 单数据库复制,仅针对该单数据库进行读写拆分
- amazon-web-services - 如何从存储在 Amazon Redshift 列中的 JSON 数组中获取字符串?
- magento-2.0 - 产品从管理员保存它在表 url_rewrite 中添加双 html URL
- python - 如何在python中使用DNN估计带有“参数”的正弦函数?
- slack - 编程 slack 为网站创建频道