gpt4 book ai didi

linux - 计算 UNIX 中文本的长度

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:39 24 4
gpt4 key购买 nike

我有两个问题:

1) 我想从我的脚本中删除每个非英语字母2)我想计算文本的长度,清除标点符号,空格等。我只是不知道这部分有什么问题

Linux 脚本:

    #!/usr/bin/bash

awk '

BEGIN { FS="" } # defining a field separator in order to treat each character one by one
{
$0 = tolower($0) # removing case distinctions
gsub(/[[:punct:]]/,"", $0) # removing every punctuation mark
gsub(/\ /, "", $0) # removing spaces
gsub(/[0-9]/, "", $0) # removing digits
gsub(/![a-z]/, "", $0) # removing every non-English letter <- This does not work

#After the removing of every possible punctuation mark, space, digit and non-English
#letter in the user-defined text, we calculate the occurence of each character and place into an array



for (i = 1; i <= NF; i++)
{
freq[$i]++
length++
}

}

但它显示了以下错误:awk:命令。第 17 行:长度++awk:命令。第 17 行:^ 意外的换行符或字符串结尾

请至少帮我解决第二个问题。我只是不知道有什么问题,一切看起来都很好。预先感谢!

最佳答案

使用awk

awk '{gsub("[^A-Za-z]", "");i+=length}END{print i}'

使用trwc

tr -C -d "A-Za-z" | wc -c

它们都删除 A-Za-z 范围内的所有字符,然后计算剩余的字符。 tr其优点或缺点取决于您的语言环境。

您还可以创建 awk脚本的方式与创建 shell 脚本的方式相同。

#!/usr/bin/awk
{ gsub("[^A-Za-z]", ""); i+=length }
END { print i }

为了获得最大的可移植性,您需要将脚本中的区域设置设置为 POSIX,或者列出每个字符。

tr -C -d "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | wc -c

关于linux - 计算 UNIX 中文本的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com