我有一个这样的CSV:
https://www.website.com,"[""example0@email.com""]"
https://www.website2.com,"[""example1@email.com"",""example2@email.com""]"
并希望它像这样:
example0@email.com
example1@email.com
example2@email.com
我想把这个文件转换成一个只有电子邮件的单列列表,完全忽略网站列表。但也有一个网站可能会回复10封邮件,所以我想把它们都放在同一个列里。我如何将这个CSV写入一个新的CSV中,只有一列电子邮件…(另一个单独的问题是,CSV是最好的方法吗?是否有像元组这样更快的方法?)我已经用了20年的excel了,所以我开始熟悉Python了。仍然像电子表格一样思考!由于
import csv
with open('sample.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
emails = list()
for row in csv_reader:
for row in row[1:]:
for email in row.split(","):
emails.append(email.strip("[]").strip("""))
with open('answer.csv', 'w') as f:
writer = csv.writer(f)
for email in emails:
writer.writerow([email])
我建议您查看python Pandas包。如果你喜欢excel,你可能会喜欢熊猫。
导入包
import pandas as pd
读取数据(您将使用pd.read_csv()
data = dict(col1 = ['https://www.website.com','https://www.website2.com'],
col2 = ['"[""example0@email.com""]"','"[""example1@email.com"",""example2@email.com""]"'])
df = pd.DataFrame(data)
从这里开始,您可以采用多种方法,要么只处理感兴趣的列(df[col2]),要么展开整个表。首先,需要摆脱额外的"括号,再次使用字符串对象的一些功能属性:
df['col2'] = df['col2'].str.replace(r'"','')
df['col2'] = df['col2'].str.replace(r'[','')
df['col2'] = df['col2'].str.replace(r']','')
将电子邮件转换为字符串列表而不是长字符串。字符串有拆分的能力:
df['col2'] = df['col2'].str.split(',')
现在爆炸:
df = df.explode('col2')
如果你真的只想要电子邮件,就看看:
df['col2']
要使其成为csv文件,可以使用df。to_csv文件。文档中有很多很好的例子。
import pandas as pd
df = pd.read_csv("your_csv.csv")
sites = df.iloc[0]
sites_list = []
for site in sites:
site = site.split(sep=",")
for s in site:
sites_list.append(s)
result = [i.replace("[", "").replace("]", "").replace('"', "") for i in sites_list]
>> ['https://www.website2.com', 'example1@email.com', 'example2@email.com']
使用强大的生成器:
import re
def read_emails(file):
with open(file, 'r') as f:
for item in f:
yield from map(lambda x: f'{x}n', re.findall(r'[w.-]+@[w.-]+', item))
def write_emails(file, items):
with open(file, 'w') as f:
f.writelines(items)
write_emails('result.txt', read_emails('test.csv'))
结果:
cat result.txt
example0@email.com
example1@email.com
example2@email.com