左手用R右手Python系列之——字元串格式化進階

關於R語言字元串格式化之前無論是專題還是案例教程中均有所涉及,今日這一篇之所以重提是因為又找到了一個很好用的字元串格式化包。

這個包的語法源於Python風格,這樣可以讓那些從Python遷移過來的R語言學習者無需額外的記憶負擔,即可平穩掌握R語言中的字元串格式化語法。

提到字元串格式化語法,我們一定能想到paste/pasteo函數,或者str_c函數,這兩個函數的用法差不多,都是通過字元串與變數之間的拼接完成字元串格式化任務,但是問題是R語言中的字元處理並不想Python中那麼靈活(僅靠「+」即可拼接字元),當一個字元串中需要插入多個變數時,拼接任務變得異常複雜。

好在R語言中保留了sprintf函數,這個源自C語言家族的字元串格式化函數,在左手用R右手Python系列推送文章中,曾經就這個問題專門寫過一篇,但是這個sprintf函數使用起來並不是特別方便,特別是同類格式需要重複定義,同樣的問題在Python的語法中也存在。

左右用R右手Python系列——字元串格式化輸出

但是Python中有另外一套字元串格式化無法,使用format函數和{}來定義,最近發現R語言中的pystr包,也模仿著Python中的這一模式定義了一套風格一致的函數,所以現在在R語言中使用字元串格式化多了一個更加高效的途徑。

項目主頁:

#https://github.com/Ironholds/pystrdevtools::install_github("nicolewhite/pystr")

備註:(如果下載失敗,可以嘗試先將zip文件下載到本地,然後使用菜單式命令進行安裝!)

library(pystr)

順序參數:

sprintf("Hello %s, my name is %s.", "World", "RainDu")#"Hello World, my name is RainDu."pystr_format("Hello {1}, my name is {2}.", "World", "RainDu")#"Hello World, my name is RainDu."

以上兩句等價。

以上方法在Python中應該寫成如下兩種形式:

print("Hello %s, my name is %s." % ("World", "RainDu"))#Hello World, my name is RainDu.print("Hello {0}, my name is {1}.".format("World", "RainDu"))#Hello World, my name is RainDu.

在設置順序參數時,pystr_format函數的優越之處在於,它真正實現了右側待插入字元參數的批量化,即如果右側傳入的字元串參數如果有多個,你可以直接傳入命名的向量或者列表。

pystr_format("Hello {thing}, my name is {name}.", thing="World", name="RainDu")pystr_format("Hello {thing}, my name is {name}.", c(thing="World", name="RainDu"))pystr_format("Hello {thing}, my name is {name}.", list(thing="World", name="RainDu"))#"Hello World, my name is RainDu."

以上三句等價,風格與Python中str.format風格嚴格保持一致。

此時左側的插入位置僅需輸入右側的對應名稱即可,左側順序與右側命名序列順序無須嚴格一致(因為有名稱可以索引)。

當然以上三句第一句看起來不是很友好,右側參數是單個傳入的,第二句第三個比較符合使用習慣。

那麼命名關鍵字參數在Python中寫法是這樣的。

print("Hello {thing}, my name is {name}.".format(thing = "World",name = "RainDu"))Hello World, my name is RainDu.my_cars <- data.frame(car=rownames(mtcars), mtcars)pystr_format("The {car} gets {mpg} mpg (hwy) despite having {cyl} cylinders.", my_cars)

藉助R語言中函數強大的向量化功能,pystr_format函數可以很容易的實現批量化插入特定字元。

supers <- data.frame( first=c("Bruce", "Hal", "Clark", "Diana"), last=c("Wayne", "Jordan", "Kent", "Prince"), is=c("Batman", "Green Lantern", "Superman", "Wonder Woman") )pystr_format("{first} {last} is really {is} but you shouldn"t call them {first} in public.", supers)

而同樣的功能要想在Python中實現,則要麼藉助循環,要麼藉助列表表達式或者高階函數(結合lmanda表達式)。

supers = { "first":["Bruce", "Hal", "Clark", "Diana"], "last":["Wayne", "Jordan", "Kent", "Prince"], "the":["Batman", "Green Lantern", "Superman", "Wonder Woman"] }

使用普通的循環格式化:

strword = []for first,last,the in zip(supers["first"],supers["last"],supers["the"]): print("{0:s} {1:s} is really {2:s} but you shouldn"t call them {1:s} in public.".format(first,last,the)) strword.append("{0:s} {1:s} is really {2:s} but you shouldn"t call them {1:s} in public.".format(first,last,the))Bruce Wayne is really Batman but you shouldn"t call them Wayne in public.Hal Jordan is really Green Lantern but you shouldn"t call them Jordan in public.Clark Kent is really Superman but you shouldn"t call them Kent in public.Diana Prince is really Wonder Woman but you shouldn"t call them Prince in public.

使用列表表達式進行格式化:

supers["strword"] = ["{0:s} {1:s} is really {2:s} but you shouldn"t call them {1:s} in public.".format(first,last,the) for first,last,the in zip(supers["first"],supers["last"],supers["the"])]{"first": ["Bruce", "Hal", "Clark", "Diana"], "last": ["Wayne", "Jordan", "Kent", "Prince"], "strword": ["Bruce Wayne is really Batman but you shouldn"t call them Wayne in public.", "Hal Jordan is really Green Lantern but you shouldn"t call them Jordan in public.", "Clark Kent is really Superman but you shouldn"t call them Kent in public.", "Diana Prince is really Wonder Woman but you shouldn"t call them Prince in public."], "the": ["Batman", "Green Lantern", "Superman", "Wonder Woman"]}

使用高階函數+匿名函數進行格式化

func = lambda x,y,z:"{0:s} {1:s} is really {2:s} but you shouldn"t call them {0:s} in public.".format(x,y,z)supers["strword2"] = list(map(func,supers["first"],supers["last"],supers["the"]))

以上便是在R語言中使用Python風格字元串格式化輸出函數的主要內容,除此之外,pystr包內還內只有很多其他常見的字元串格式化函數,很多功能在stringr包內都能找到原型,這裡僅以字元串格式化輸出為例,其他的感興趣可以自行了解,不再贅述。

在線課程請點擊文末原文鏈接:

Hellobi Live | R語言可視化在商務場景中的應用edu.hellobi.com

https://github.com/ljtyduyu/DataWarehouse/tree/master/Filegithub.com


推薦閱讀:

【數據分析·實戰】評分與銷量有相關性嗎?
從事數據工作的你,有多少數據競爭力?
Python數據分析及可視化實例之Request、BeautifulSoup

TAG:R编程语言 | Python | 数据分析 |