2013-10-13 254 views
2

我正在编写脚本以将IPTC数据添加到图像文件夹。它从EXIF信息中提取日期并将其添加到'Caption' IPTC标记中。日期后缀(第一,第二,第三,第四等)

date = iptc["DateTimeOriginal"] 
date = date.strftime('%A %e %B %Y').upcase 
iptc["Caption"] = '%s: %s (%s)' % [date, caption, location] 

该脚本除了日期输出:

Sunday 13 October 2013 

理想情况下,我想它想的输出:

Sunday 13th October 2013 

任何建议,将不胜感激。

回答

3

如果您能够(并愿意)将Ruby宝石加入组合中,请考虑ActiveSupport::Inflector。 您可以

gem install active_support

安装(您可能需要sudo

则需要在你的文件,包括ActiveSupport::Inflector

require 'active_support/inflector' # loads the gem 
include ActiveSupport::Inflector # brings methods to current namespace 

那么你可以ordinalize整数不管三七二十一:

ordinalize(1) # => "1st" 
ordinalize(13) # => "13th" 

您可能需要字符串化的手你的日期,但:

date = iptc["DateTimeOriginal"] 
date_string = date.strftime('%A ordinalday %B %Y') 
date_string.sub!(/ordinalday/, ordinalize(date.day)) 
date_string.upcase! 

,你应该对你的方式:

iptc["Caption"] = "#{date_string}: #{caption} #{location}" 
+1

解决了,稍微调整了最后一点:将{date}更改为{date_string}会给出正确的输出。非常感谢你! –

+0

就在!我的坏 - 相应地更新! – rmosolgo

3

如果您不希望要求从的ActiveSupport的帮手,或许只是复制一个特定的方法做的工作:

# File activesupport/lib/active_support/inflector/methods.rb 
def ordinalize(number) 
    if (11..13).include?(number.to_i.abs % 100) 
    "#{number}th" 
    else 
    case number.to_i.abs % 10 
     when 1; "#{number}st" 
     when 2; "#{number}nd" 
     when 3; "#{number}rd" 
     else "#{number}th" 
    end 
    end 
end 

在你的脚本方法,您的代码更改为:

date = date.strftime("%A #{ordinalize(date.day)} %B %Y") 
相关问题