我正在尝试解析原始电子邮件。所需的结果是包含特定标题的行的哈希值。
这是Ruby文件:
raw_email = File.open("sample-email.txt", "r")
parsed_email = Hash.new('')
raw_email.each do |line|
puts line
header = line.chomp(":")
puts header
if header == "Delivered-To"
parsed_email[:to] = line
elsif header == "From"
parsed_email[:from] = line
elsif header == "Date"
parsed_email[:date] = line
elsif header == "Subject"
parsed_email[:subject] = line
end
end
puts parsed_email
这是原始电子邮件:
Delivered-To: user1@example.com
From: John Doe <user2@example.com>
Date: Tue, 12 Dec 2017 13:30:14 -0500
Subject: Testing the parser
To: user1@example.com
Content-Type: multipart/alternative;
boundary="123456789abcdefghijklmnopqrs"
--123456789abcdefghijklmnopqrs
Content-Type: text/plain; charset="UTF-8"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec
odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla
quis sem at nibh elementum imperdiet. Duis sagittis ipsum.
--123456789abcdefghijklmnopqrs
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam.
Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis
ipsum.<br clear="all">
</div>
--089e082c24dc944a9f056028d791--
puts语句仅供我自己测试,以查看数据是否被传递。
我得到的是每个完整行放两次,最后放一个空哈希。
我也尝试将不同的位更改为字符串或数组,我也尝试使用line.split(":", 1)
代替line.chomp(":")
有人可以解释为什么这不起作用吗?
答案 0 :(得分:1)
试试这个
raw_email = File.open("sample-email.txt", "r")
parsed_email = {}
raw_email.each do |line|
case line.split(":")[0]
when "Delivered-To"
parsed_email[:to] = line
when "From"
parsed_email[:from] = line
when "Date"
parsed_email[:date] = line
when "Subject"
parsed_email[:subject] = line
end
end
puts parsed_email
=> {:to=>"Delivered-To: user1@example.com\n", :from=>"From: John Doe <user2@example.com>\n", :date=>"Date: Tue, 12 Dec 2017 13:30:14 -0500\n", :subject=>"Subject: Testing the parser\n"}
<强>解释强>
您需要在:
上拆分并先选择。像这样line.split(":")[0]