0

R新手在这里我有看起来像这样的数据:

{'id': 19847005, 'profile_sidebar_fill_color': u'http://pbs.foo.com/profile_background', 'profile_text_color': u'333333', 'followers_count': 1105, 'location': u'San Diego, CA', 'profile_background_color': u'9AE4E8', 'listed_count': 43, '009', 'time_zone': u'Pacific Time (US & Canada)', 'protected': False}

我想从此文本中提取位置数据:加利福尼亚州圣地亚哥。

我一直在尝试使用这个 stringr 包来实现这一点,但不能完全获得正则表达式来捕获城市和州。有时状态会存在,有时不存在。

location_pattern <- "'location':\su'(\w+)'"
rawdata$location <- str_extract(rawdata$user, location_pattern)
4

3 回答 3

2

其他人提供了可能的解决方案,但没有解释您的尝试可能出了什么问题。

str_extract函数使用不理解的 POSIX 扩展正则表达式\w\s,这些是 Perl 正则表达式特有的。您可以改用perlstringr 包中的函数,然后它会识别快捷方式,或者您可以使用[[:space:]]代替\s[[:alnum:]_]代替\w尽管您更可能需要类似[[:alpha], ]or的东西[^']

此外,R 的字符串解析器在将字符串传递给匹配函数之前对其进行了处理,因此如果您使用该函数(或 R 中的其他正则表达式函数),您将需要\\s\\w字符串perl。第一个\转义第二个,以便将单个\保留在字符串中以被解释为正则表达式的一部分。

于 2014-12-30T23:08:05.740 回答
2

你可以试试

str_extract_all(str1, perl("(?<=location.: u.)[^']+(?=')"))[[1]]
#[1] "San Diego, CA"
于 2014-12-30T20:11:27.337 回答
2

它看起来像一个 json 字符串,但如果您不太关心它,那么也许这会有所帮助。

library(stringi)

ss <- stri_split_regex(x, "[{}]|u?'|(, '(009')?)|: ", omit=TRUE)[[1]]
(m <- matrix(ss, ncol = 2, byrow = TRUE))
#      [,1]                         [,2]                                   
# [1,] "id"                         "19847005"                             
# [2,] "profile_sidebar_fill_color" "http://pbs.foo.com/profile_background"
# [3,] "profile_text_color"         "333333"                               
# [4,] "followers_count"            "1105"                                 
# [5,] "location"                   "San Diego, CA"                        
# [6,] "profile_background_color"   "9AE4E8"                               
# [7,] "listed_count"               "43"                                   
# [8,] "time_zone"                  "Pacific Time (US & Canada)"           
# [9,] "protected"                  "False"                            

所以现在您在左列中有 ID 名称,在右列中有值。如果需要,从这一点重新组装 json 可能会很简单。

此外,关于 json-ness,我们可以强制m转换为 a data.frame(或将其保留为矩阵),然后使用jsonlite::toJSON

library(jsonlite)
json <- toJSON(setNames(as.data.frame(m), c("ID", "Value")))
fromJSON(json)
#                           ID                                 Value
# 1                         id                              19847005
# 2 profile_sidebar_fill_color http://pbs.foo.com/profile_background
# 3         profile_text_color                                333333
# 4            followers_count                                  1105
# 5                   location                         San Diego, CA
# 6   profile_background_color                                9AE4E8
# 7               listed_count                                    43
# 8                  time_zone            Pacific Time (US & Canada)
# 9                  protected                                 False
于 2014-12-30T22:20:08.260 回答