2013-10-13 86 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") 
相關問題