我需要编写一个程序来读取维基百科源文件并提取所有指向其他网页的链接。所有的网页看起来都像例子:
<a href="/wiki/PageName" title="PageName">Chicken</a>
我基本上需要将/wiki/之后的 PageName 与标题匹配,如果它们相同,如上,则仅在终端上显示 PageName。
但是,下面的应该不会被匹配,因为它和上面的格式不一样:
<a href="http://chicken.com>Chicken</a>
(这是维基百科上一个普通网站的链接)
<a href="/wiki/Chicken >Chicken</a
>(缺少标题=部分)
我试图实现的输出看起来像这样:
Example output I am trying to achieve
我已经在这方面工作了很长一段时间,并且能够做到以下几点:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE * file;
file = fopen(argv[1], "r");
char line[512];
char* search;
while(!feof(file)){
fgets(line,512,file);
search = strstr( line, "<a href=\"/wiki/");
if(search != NULL){
puts(search);
}
}
}
代码只过滤到/wiki/但我从这里开始一片空白。我尝试了很多搜索但无法找到线索。帮助将不胜感激。
最佳答案
您可以使用 while(fgets(line,512,file))
代替 while(!feof(file))
并通过添加几个验证您的最终代码预期输出看起来像,
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif // MSC
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * file;
if (argc != 2)
{
return -1;
}
file = fopen(argv[1], "r");
if (!file)
{
return -1;
}
char line[512];
char* search;
while (fgets(line, 512, file)) {
search = strstr(line, "<a href=\"/wiki/");
if (search != NULL) {
char *title = _strdup(search);
if (title)
{
char* start = strstr(title, ">");
char* end = strstr(start, "<");
if (end)
{
*end = 0;
}
if (strlen(start) >= 2)
{
puts(start + 1);
}
free(title);
title = 0;
}
}
}
fclose(file);
file = NULL;
return 0;
}
关于c - 使用 C 提取 Wiki 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713494/