php - 如果单词在同一段落中匹配,则 shell 或 PHP 删除 HTML 注释
问题描述
我需要验证 HTML 注释中的单词是否包含在同一行中,在这种情况下,删除注释。否则,保留评论。
同时,脚本需要忽略代词、副词、冠词。我已经有一个清单,超过 100 百字。像这样:
“那个”、“这个”、“我”、“我”、“你”、“她”、“她”、“他”、“他”、“它”、“他们”、“他们”、“那个” ”、“威奇”等...
这是一行的示例:
text <!-- They are human # life --> text text <!-- the rights --> text the human text
运行脚本后:
text text text <!-- the rights --> text the human text
恢复:
- 在同一行中可以有很多评论,而不仅仅是一个。
- 脚本需要忽略我的代词、副词等列表...
- 脚本需要忽略其他评论的话。
- 不敏感的情况。
- 这些文件有超过一千行。
- 通常在评论中我有这个字符#(我希望不是问题)。
解决方案
正如其他人所提到的,您应该进行一些研究,说明您尝试过什么以及为什么它不起作用。
话虽如此,我发现这是一个有趣的小挑战,所以我决定试一试。
我假设有两个文件,“file.html”我们要修改,“words.txt”列出要忽略的单词,用换行符 (\n) 分隔。这个脚本应该可以解决问题:
#!/bin/bash
FILE="file.html"
WORDS="words.txt"
#Set array delimiter to '\n':
IFS=$'\n'
#Find all comments within the file:
comments="$(cat $FILE | grep -oP '<!--[^<]+-->' | sort | uniq)"
for comment in $comments; do
#Words In Comment. Gets all words in the comment.
wic="$(echo $comment | head -1 | grep -oP '[^\s]+' | grep -v '<' | grep -v '>')"
words="$(cat $WORDS)"
#Filtered Words. It's $wic without any of the words in words.txt
fw="$(echo $wic $words $words | tr ' ' '\n' | sort | uniq -u)"
#if any remain
if [ ! -z "$fw" ]
then
for word in $fw; do
#Gets all lines with both the comment and the word outside the comment
lines="$(cat $FILE | grep -P "$comment.+$word|$word.+$comment")"
#If it finds any
if [ ! -z "$lines" ]
then
for line in $lines; do
#Generate the replacement line
replace="$(echo $line | sed "s/$comment//g")"
#Replace the line with the replacement in the file
sed -i "s/$line/$replace/g" $FILE
done
fi
done
fi
done
它并不完美,但可以完成工作。在具有以下内容的文件上对其进行了测试:
text <!-- foo # --> foo
text <!-- bar # --> foo
text <!-- bar # --> bar
text <!-- bar # --> text <!-- something # --> something bar
text <!-- foo # --> text <!-- bar # --> text foo bar
使用以下 words.txt:
foo
并得到了预期的结果:
text <!-- foo # --> foo
text <!-- bar # --> foo
text bar
text text something bar
text <!-- foo # --> text text foo bar
推荐阅读
- java - 在 Android Studio 中制作动画
- python - Python regex - 贪婪的量词在所有情况下都不起作用
- python - Pandas Groupby:具有多个分类的“观察到”参数
- python - 为什么使用均方误差进行图像差异?为什么要使用直方图来计算呢?
- python - 在python的另一个字符串中找到一个字符串
- javascript - 使用 httppost 将 paymentIntentSecret 获取到 Javascript
- sql - 如何使案例语句显示在 1 行上?我得到一个错误,除非我把一个分组,但然后它分组并产生2个不同的行
- rust - 使用 to_string 是按行读取文件并按空格分割的最干净的方法吗?
- xcode - 从 Xcode 中删除领域模型对象
- excel-formula - Excel =IF(value >= value) 不返回正确答案