從句子中提取單詞
參數
- string
-
輸入向量。或者是一個字符向量,或者是可強製轉換為一個的東西。
- start, end
-
給出要提取的單詞範圍(包括)的整數向量對。如果為負數,則從最後一個單詞開始倒數。
默認值選擇第一個單詞。
- sep
-
單詞之間的分隔符。默認為單個空格。
例子
sentences <- c("Jane saw a cat", "Jane sat down")
word(sentences, 1)
#> [1] "Jane" "Jane"
word(sentences, 2)
#> [1] "saw" "sat"
word(sentences, -1)
#> [1] "cat" "down"
word(sentences, 2, -1)
#> [1] "saw a cat" "sat down"
# Also vectorised over start and end
word(sentences[1], 1:3, -1)
#> [1] "Jane saw a cat" "saw a cat" "a cat"
word(sentences[1], 1, 1:4)
#> [1] "Jane" "Jane saw" "Jane saw a" "Jane saw a cat"
# Can define words by other separators
str <- 'abc.def..123.4568.999'
word(str, 1, sep = fixed('..'))
#> [1] "abc.def"
word(str, 2, sep = fixed('..'))
#> [1] "123.4568.999"
相關用法
- R stringr str_which 查找匹配索引
- R stringr str_extract 提取完整的匹配項
- R stringr case 將字符串轉換為大寫、小寫、標題大小寫或句子大小寫
- R stringr str_subset 查找匹配元素
- R stringr str_escape 轉義正則表達式元字符
- R stringr str_trim 刪除空格
- R stringr str_sub 使用子字符串的位置獲取和設置子字符串
- R stringr modifiers 使用修飾符函數控製匹配行為
- R stringr str_replace_na 把NA變成“NA”
- R stringr str_trunc 將字符串截斷至最大寬度
- R stringr str_match 從匹配中提取組件(捕獲組)
- R stringr stringr-data 用於練習字符串操作的示例字符向量
- R stringr invert_match 將匹配位置切換到非匹配位置
- R stringr str_like 以與 SQL 的 LIKE 運算符相同的方式檢測模式
- R stringr str_length 計算長度/寬度
- R stringr str_detect 檢測是否存在匹配
- R stringr str_count 計算匹配次數
- R stringr str_split 將字符串分成幾段
- R stringr str_unique 刪除重複的字符串
- R stringr str_remove 刪除匹配的模式
- R stringr str_pad 將字符串填充到最小寬度
- R stringr str_equal 判斷兩個字符串是否相等
- R stringr str_view 查看字符串和匹配項
- R stringr str_glue 用膠水插補
- R stringr str_conv 指定字符串的編碼
注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Extract words from a sentence。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。