我正试图从文件中的句子中删除停止词?
停止字,我的意思是:[I, a, an, as, at, the, by, in, for, of, on, that]
我在文件my_text.txt
:中有这些句子
Unix系统设计的主要目标之一是创建一个促进高效程序的环境
然后我想从上面的句子中删除停止词
我使用了这个脚本:
array=( I a an as at the by in for of on that )
for i in "${array[@]}"
do
cat $p | sed -e 's/<$i>//g'
done < my_text.txt
但输出是:
Unix系统设计的主要目标之一是创建一个促进高效程序的环境
预期输出应为:
Unix系统设计的一个主要目标是创建一个环境促进高效程序
注意:我想删除删除停止字而不是重复的字?
像这样,假设$p
是一个现有文件:
sed -i -e "s/<$i>//g" "$p"
必须使用双引号,而不是单引号来展开变量。
-i
开关取代第行中的。
了解如何在shell中正确报价,这非常重要:
"双引号"每个包含空格/元字符的文字和每个扩展:
"$var"
、"$(command "$var")"
、"${array[@]}"
、"a & b"
。使用'single quotes'
作为代码或文字$'s: 'Costs $5 US'
、ssh host 'echo "$HOSTNAME"'
。请参阅
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
最后
array=( I a an as at the by in for of on that )
for i in "${array[@]}"
do
sed -i -e "s/<$i>s*//g" Input_File
done
奖金
尝试不使用s*
来理解我为什么添加此regex
awk中的一个。这是一个有效的道具,但需要正确的标点符号处理,然后再进行一些处理(幸运的是,你的数据没有(:
$ awk '
NF==FNR { # process stop words
split($0,a,/,/) # comma separated without space
for(i in a) # they go to b hash
b[a[i]]
next
}
{ # reading the text
for(i=1;i<=NF;i++) # iterating them words
if(!($i in b)) # if current word notfound in stop words
printf "%s%s",$i,OFS # output it (leftover space in the end, sorry)
print "" # newline in the
}' words text
输出:
One primary goals design Unix system was to create environment promoted efficient program
为什么awk?Shell是一种用于管理文件和启动程序的工具。除此之外,其他地方处理得更好。
可以使用这个脚本:
while read p
do
echo $p | sed -e 's/<I>//g' | sed -e 's/<an>//g' | sed -e 's/<a>// g'|sed -e 's/<as>//g'|sed -e 's/<at>//g'|sed -e 's/<the>//g' | sed -e 's/<by>//g' | sed -e 's/<in>//g' | sed -e 's/<for>//g' | sed -e 's/<of>//g' | sed -e 's/<on>//g' > my_text.txt
cat my_text.txt
done < my_text.txt
然后输出它必须像这样:
Unix系统设计的一个主要目标是创造一个高效的环境程序
我也非常喜欢在文本处理中使用awk。假设输入数据是mytext.txt
文件,而script
是包含以下代码的文件,只需将其作为awk -f mytext.txt script
运行即可。
此外,这应该可以通过更改stopwords
变量,在需要时更容易地更改停止字。请记住,mytext.txt
和stopwords
都必须只包含空格分隔的单词。
BEGIN {
stopwords = "I a an as at the by in for of on that"
split(stopwords, wordarray)
ORS = " "
RS = " "
}
{
equals = 0
for (w in wordarray)
if ($0 == wordarray[w])
equals = 1
if (equals == 0) print $0
}