我有一封电子邮件列表,只想提取域并计算每个域出现的次数:
电子邮件:
best@yahoo.com
hello@gmail.com
everybody@gmail.com
bye@gmail.com
day@yahoo.com
table.blue@gmail.com
life@yahoo.com
脚本:
import re
from collections import Counter
with open("mails.txt", "r") as f:
texte = f.read().split('\n')
for line in texte:
newline = re.search("@[\w.]+", line)
newmail = newline.group()
mails_value = Counter(newmail).most_common()
print (mails_value)
输出:
[('@',1),('g',1),('6',1),('5',1),('。',1),('f',1 ),('r',1)]
回溯(最近通话最近一次):
中的文件“ counting.py”,第10行
newmail = newline.group()
AttributeError:'NoneType'对象没有属性'group'
好的输出:
@ yahoo.com 3
@ gmail.com 4
答案 0 :(得分:2)
您非常接近-无需将文件拆分为行,只需使用re.findall
,re.MULTILINE
和模式@(.*)$
import re
import collections
with open("mails.txt") as f:
text = f.read()
domains = re.findall(r'@(.*)$', text, re.MULTILINE)
mails_value = collections.Counter(domains)
# outputs with example: Counter({'gmail.com': 4, 'yahoo.com': 3})
答案 1 :(得分:2)
您不需要正则表达式。如果您可以确信所有输入内容都是格式正确的电子邮件,那么就足够了:
from collections import defaultdict
domain_count = defaultdict(lambda: 0)
with open("mails.txt", "r") as f:
texte = f.readlines()
for line in texte:
domain = line.split('@')[-1]
domain_count[domain] += 1
print (domain_count)
答案 2 :(得分:2)
正则表达式将使您免于创建不必要的列表。
Quant
输出
import re
from collections import Counter
with open("mails.txt", "r") as f:
texte = f.read().split('\n')
l=[]
for line in texte:
p=re.compile("(?<=@)[^.]+(?=\.)")
newline = p.search(line)
if(newline):
newmail = newline.group(0)
l.append(newmail)
Counter(l)
答案 3 :(得分:1)
您可以使用split
texte = "life@yahoo.com"
texte.split("@")
['life', 'yahoo.com']
答案 4 :(得分:1)
进行2次分割。第二个带有@.。然后附加最后一项并将计数器应用于列表
import re
from collections import Counter
with open("mails.txt", "r") as f:
texte = f.read().split('\n')
domains = []
for line in texte:
line = line.split('@')
if line[-1] != "":
domains.append(line[-1])
mails_value = Counter(domains).most_common()
print(mails_value)
[('gmail.com', 4), ('yahoo.com', 3)]
答案 5 :(得分:1)
import re
from collections import Counter
mails = []
with open("mails.txt", "r") as f:
texte = f.read().split()
for i in texte:
mails.append(re.search("@[\w.]+", i).group())
mails_value = Counter(mails).most_common()
print mails_value