How can I extract Chinese characters after a space?
The original data is below:
10:36 不願做奴隸的人們 然後看你有沒有在時間內申覆。
10:37 千里之外 真的很無奈
10:37 不願做奴隸的人們 如果五天內你沒注意信心,表示你默認。
The data that I need is:
不願做奴隸的人們
千里之外
不願做奴隸的人們
The code that I used is:
filedata <- scan(file = ,what = "",sep = "\n",encoding = "UTF-8")
#定义数据框和变量
data <- data.frame(user_name = c(),date = c(),date = c())
date <- vector(length=length(filedata))
time <- vector(length=length(filedata))
user_name <- vector(length=length(filedata))
text <- vector(length=length(filedata))
#截取用户名、时间和日期
pat1 = '[0-9]{4}/[0-9]{2}/[0-9]{2}' #表示日期的正则表达式
pat2 = '[0-9] :[0-9] ' #表示时间的正则表达式
for(i in 1: length(filedata)){
dt_pattern1 <- grepl(pat1,filedata[i]) #grepl函数识别每条记录中的日期部分
dt_pattern2 <- grepl(pat2,filedata[i]) #grepl函数识别每条记录中的时间部分
if(dt_pattern1 == TRUE){
date[i] <- substr(filedata[i],1,10)
}
if(dt_pattern2 == TRUE){
time[i] <- substr(filedata[i],1,5)
user_name[i] <- substr(filedata[i], 7, "\\s")
}
}
data <- rbind(data, data.frame(Name = user_name,date = date,time = time))
I need to create a Name variable, but it has a warning message:
NAs introduced by coercion
Can anyone help to debug? Thank you very much!
CodePudding user response:
If your data is a vector of strings, you can split the strings by any white space, and extract the second element in each split string.
library(stringr)
user_name <- c(
"10:36 不願做奴隸的人們 然後看你有沒有在時間內申覆。",
"10:37 千里之外 真的很無奈",
"10:37 不願做奴隸的人們 如果五天內你沒注意信心,表示你默認。"
)
str_split(user_name, "\\s ", simplify = T)[, 2]
[1] "不願做奴隸的人們" "千里之外" "不願做奴隸的人們"
CodePudding user response:
Assuming you just want the first word from the username, you could use sub()
here:
user_name <- "不願做奴隸的人們 如果五天內你沒注意信心,表示你默認。"
first <- sub("(\\S ).*", "\\1", user_name)
first