我正在尝试制作一个bash脚本来执行以下任务:
输入:电影或系列名称
Ouput:这部电影的一些细节,例如导演,描述和其他细节
我可以正确检索想要的电影的网页,并使用wget
和其他命令将其保存为文件,因此,如何从该文件中提取描述内容并使用进行打印echo
。
搜索后:我发现我应该使用grep
和regex patterns
得到想要的东西,但是我在正则表达式模式中遇到了问题。
这是我要从中提取描述的文件的一部分
<meta name="description" content="Directed by Sam Raimi. With Tobey Maguire, Kirsten Dunst, Willem Dafoe, James Franco. When bitten by a genetically modified spider, a nerdy, shy, and awkward high school student gains spider-like abilities that he eventually must use to fight evil as a superhero after tragedy befalls his family." />
例如:
输入:蜘蛛侠
输出:由山姆·雷米(Sam Raimi)执导。与Tobey Maguire,Kirsten Dunst,Willem Dafoe,James Franco一起。当一个被基因改造的蜘蛛咬伤时,一个书呆子,害羞,笨拙的高中生会获得类似蜘蛛的能力,在悲剧降临他的家人之后,他最终必须用它来作为超级英雄与邪恶作斗争。
那么从文件中获取描述内容的命令或正确的正则表达式模式是什么?
grep 'meta name="description" content="' yourfile.dat | cut -d '"' -f4
问题是您的整体都meta
在同一行上。
因此,使用grep不仅要抓线,而且不会分裂。
在这里,您grep
可以获取meta
行,cut
并"
以定界符的形式获取第四部分。
您也可以这样做:
sed 's/.*meta name="description" content="\(.*\)".*/\1/' yourfile.dat
使用解析器:
xmllint --html --xpath 'string(/html/head/meta[@name="description"]/@content)' yourfile.dat
输出:
Directed by Sam Raimi. With Tobey Maguire, Kirsten Dunst, Willem Dafoe, James Franco. When bitten by a genetically modified spider, a nerdy, shy, and awkward high school student gains spider-like abilities that he eventually must use to fight evil as a superhero after tragedy befalls his family.
在python中:
lst = []
with open('yourfile.dat', 'r') as msg:
for line in msg:
if 'meta name="description"' in line:
lst.append(line.split('"')[3])
当然,您也可以在Python和bash中使用多个字符定界符Awk
。这避免了在具有相似特性的线的情况下出现误报。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句