1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
library(ggplot2)
library(dplyr)
library(stringr)   #문자열 처리 패키지.
 
= "R is a programming language and software environment for statistical computing and graphics supported by the R Foundation for Statistical Computing. The R language is widely used among statisticians and data miners for developing statistical software and data analysis. Polls, surveys of data miners, and studies of scholarly literature databases show that R's popularity has increased substantially in recent years.
R is a GNU package. The source code for the R software environment is written primarily in C, Fortran, and R. R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems. While R has a command line interface, there are several graphical front-ends available"
 
 
str_extract(r, "software environment")                   #첫번쨰로 발견되는 문자열 추출.
str_extract_all(r, "software environment")               #매칭되는 모든 문자열 추출.
str_extract_all(r, "software environment",simplify = T)  #리스트가 아닌 매트릭스로 리턴.
 
#첫 글자가 대문자로 시작되는 단어들 추출  *: 0개이상 = {0, } , +: 1개이상 = {1 , }
#e = str_extract_all(r, "[[:upper:]]+[[:alpha:]]+")
= str_extract_all(r, "[[A-Z]]+[[a-zA-Z]]+")
 
table(e)
 
#등장 위치
str_locate    (   r, "software environment"  )
str_locate_all(   r, "software environment"  )
 
 
#grouping
# [,1] 에는 매칭된 전체 문자열 , [,2]에는 첫번째 그룹에 매칭된 문자열이 리턴된다.
 
str_match_all(r,"([[:alpha:]]+)\\."#문자열 r에서 매칭되는 패턴의 ()안에 문자열을 리턴.
 
#[[1]]
#         [,1]          [,2]       
# [1,] "Computing." "Computing"
# [2,] "analysis."  "analysis" 
# [3,] "years."     "years"    
# [4,] "package."   "package"  
# [5,] "R."         "R"        
# [6,] "systems."   "systems"
 
 
#첫글자가 대문자로 시작하는 단어들의 위치
= str_locate_all(r, '[[:upper:]]{1}[[:alpha:]]*')
 
df = data.frame(l[[1]])
df
 
#첫글자가 대문자로 시작하는 단어들 추출
= str_extract_all(r, '[[:upper:]]{1}[[:alpha:]]*')[[1]]
df$w = e
 
df$l =  df$end - df$start + 1
df
 
#전처리 과정중 고유명사 처리. 하나의 단어로 만들어줘야 한다.
str_replace(r, "software environment",  "software_environment")
temp = str_replace_all(r, "software environment",  "software_environment")
 

str_extract_all(r, "software_environment |software|environment ")  #정규표현식의 or 조건은 |로 구분해서 넣어주면 된다.
table(str_extract_all(r, "software_environment |software|environment "))
table(str_extract_all(temp, "software_environment |software|environment ")) #앞쪽의 조건에 해당되서 추출된 단어는 뒤쪽의 조건에 같이 해당되어도 중복 추출되지 않는다.
 
#특정 글자로 끝나는 문자열의 정규식
str_replace_all(r, "\\bg","&")  #g로 시작하는 글자. \\b : blank
str_replace_all(r, "g\\b","&")  #g로 끝나는   글자.
 
#R로 끝나는 문자열의 정규식 
temp = str_replace_all(r, "R\\b","R_computor.language_   ")  #R로 끝나는   글자.
temp = str_replace_all(temp, "C\\b","C_computor.language_")  #C로 끝나는   글자.
 
#paste(s,".",sep = "") 각 문자열 벡터에 특정 문자 붙이기.
 
#문단 나누기
para = str_split(r, "\n")[[1]] #리스트 -> 벡터
 
#문장 나누기
= str_split(para, "\\. ")    #스플릿을 하기 전에는 벡터로 만들어 줘야 한다.
s
 
#단어 나누기
s  = unlist(s)
s2 = s[c(4,7)]  # 불연속 인덱스 두개를 참조하려면 c함수로 묶어준다..!
 
length(unlist(str_split(s2," ")))      #벡터 컬럼의 갯수는 count 가 아닌 length로 구한다...!
 
#str_split_pixed
str_split_fixed(s2, " "5 )            #벡터 하나당 구분자 " "를 기준으로 5번만 나눈다. 그이후는 잘라지지 않는다.
str_split_fixed(s2, " "13)            #벡터 하나당 구분자 " "를 기준으로 13개로 나눈다. 부족한 곳은 ""로 나온다.
 
 
#
ls = rep(NA,length(unlist(s)))  #NA 7개 만들기 s 안에 문장 7개와 같은 갯수.!
 
#for문을 사용해서 단어수를 계산.
for(i in 1:length(ls)){
    ls[i] = length(unlist(str_split(s[i], " "))) 
}
 
#최대 단어수를 기준으로 문장 * 단어 행렬 구성.
ml = max(ls)
#7 * 21 행렬이 되면 된다.
 
#각 벡터의 문장을 " "를 기준으로 잘라서 21개의 컬럼으로 분리. => matrix
sm = str_split_fixed(s, " ", ml) 
sm
 
df = data.frame(sm) 
 
wordLength = ml               #21
sentLength = length(s)        #7
 
colnames(df) = paste("word",rep(1:wordLength),sep=""  )   #컬럼 이름을 word1~word21로 변경
rownames(df) = paste("sent",rep(1:sentLength), sep=".")   #행 이름을 sent.1~sent.7로 변경
 
df[3,1:10]


#문자열 안에서 특정 패턴의 등장횟수.
str_count(r,"R")
str_count(para, "R")
str_count(s, "R")
str_count(s,"[sS]tat[a-z]+") #또는 "(s | S)tat"
###출력결과의 위치를 정렬
name = c("joe", "jack", "jackie", "jefferson")
donation = c("$1","$111","$11111","$111111")
df = data.frame(name,donation) #두벡터 합치기.
df
###1이 오른쪽으로 정렬 되있다.
# name donation
# 1 joe $1
# 2 jack $111
# 3 jackie $11111
# 4 jefferson $111111


#왼쪽으로 정렬방법
name2 = str_pad(df$name, width = 15, side = "right", pad = " ") #right , left, both 가능 오른쪽에 pad를 주면 왼쪽으로 정렬된다.
donation2 = str_pad(df$name, width = 15, side = "both", pad = "~")
df2 = data.frame(name2,donation2)
df2

### 문자열 반복
rep("soft", 3)
str_dup("soft", 3) #duplicate 문자열 하나에 다들어간다..!
###부분 문자열 추출
str_sub(s, 1, 30)
###글자수의 갯수
str_length(s)
nchar(s) #같은 기능. base 패키지에 포함.

###글자의 공백제거
name3 = str_trim(df2$name2,side='right') #문자열 내의 공백제거
donation3 = str_trim(str_replace_all(df2$donation2, "~", " "), side = 'both') #~를 " "로 치환한후 공백 제거.


cs


+ Recent posts