Engee 文档
Notebook

文本搜索和替换

处理文本数据通常涉及搜索和替换子字符串。 有几个函数可以查找文本并返回各种信息:一些函数确认文本存在,其他函数计算文本片段的重复次数,查找索引或提取子字符串。


文本搜索

要确定是否存在文本片段,可以使用以下函数 occursin(). 逻辑值1对应于true,0对应于false。

In [ ]:
txt = "she sells seashells by the seashore"
TF = occursin("sea", txt)
Out[0]:
true

您可以使用该函数计算此文本出现的次数 count().

In [ ]:
n = count("sea", txt)
Out[0]:
2

要确定文本所在的位置,请使用函数 findall(),它返回与文本片段*"sea"*匹配的字符的索引。

In [ ]:
idx = findall("sea", txt)
Out[0]:
2-element Vector{UnitRange{Int64}}:
 11:13
 28:30

在字符串数组中搜索文本

搜索和替换功能还允许您在多元素数组中查找文本。 例如,在几首歌曲的名称中找到颜色的名称。

In [ ]:
songs = ["Penny Lane", "Yellow Submarine","Blackbird"]
colors = ["Red", "Yellow", "Black"]

TF = occursin.(colors,songs)
Out[0]:
3-element BitVector:
 0
 1
 1

要显示包含颜色名称的歌曲列表,请使用TF逻辑数组作为原始歌曲数组中的索引。 这种方法称为逻辑索引。

In [ ]:
songs[TF]
Out[0]:
2-element Vector{String}:
 "Yellow Submarine"
 "Blackbird"

匹配模式

除了搜索"海"或"黄"等文字文本外,您还可以搜索与模式匹配的文本。 有许多预定义的模式,如数字,以搜索数字序列。

In [ ]:
address = " Sesame Street, New York, NY 10128"
nums = match(r"\d+", address)
Out[0]:
RegexMatch("10128")

您可以组合模板,使您的搜索更准确。 例如,查找以字母"S"开头的单词。 使用字符串指定"S"字符,并使用lettersPattern查找该字符之后的其他字母。

In [ ]:
lettersPattern = r"[a-zA-Z]+"
pat = "N" * lettersPattern
StartWithS = match.(pat, address).match
Out[0]:
"New"

在Engee中处理文本的其他函数可以在[文本字符串]部分找到(https://engee.com/helpcenter/stable/julia/base/strings.html )。