我想從解析文本中解析名詞短語(NN,NNP,NNS,NNPS)。例如: -使用C/C++解析來自解析文本的名詞短語
Input sentence -
John/NNP
works/VBZ
in/IN
oil/NN
industry/NN
./.
Output: John Oil Industry
我感到困惑的邏輯,因爲我需要搜索字符串,例如/NN
,/NNP
,/NNS
和/NNPS
和之前打印上一個字。 使用C或C++解析名詞短語的邏輯是什麼?
我自己嘗試是以下幾點:
char* SplitString(char* str, char sep
{
return str;
}
main()
{
char* input = "John/NNP works/VBZ in/IN oil/NN industry/NN ./.";
char *output, *temp;
char * field;
char sep = '/NNP';
int cnt = 1;
output = SplitString(input, sep);
field = output;
for(temp = field; *temp; ++temp){
if (*temp == sep){
printf(" %.*s\n", temp-field, field);
field = temp+1;
}
}
printf("%.*s\n", temp-field, field);
}
我的修改如下:
#include <regex>
#include <iostream>
int main()
{
const std::string s = "John/NNP works/VBZ in/IN oil/NNS industry/NNPS ./.";
std::regex rgx("(\\w+)\/NN[P-S]{0,2}");
std::smatch match;
if (std::regex_search(s.begin(), s.end(), match, rgx))
std::cout << " " << match[1] << '\n';
}
我得到的輸出是唯一的 「約翰」。其他/ NNS標籤不會來。
我的第二個辦法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char text[] = "John/NNP works/VBZ in/IN oil/NN industry/NN ./.";
char** tokens;
//printf("INPUT SENTENCE=[%s]\n\n", text);
tokens = str_split(text, '');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
與輸出是:
[John/NNP]
[works/VBZ]
[in/IN]
[oil/NN]
[industry/NN]
[./.]
我只想/NNP
和/NN
解析數據,即John
,oil
和industry
。如何得到這個?將正則表達式的幫助?如何在C中使用正則表達式與C++相同?
我對這個邏輯感到困惑。我正在嘗試搜索/ NN,/ NNP,/ NNS和/ NNPS等字符串,然後在「/」之前打印所有字符,直到獲得空格。 –
@New_Programmer應該關於工作。 – Magisch
@Haris不,它不被稱爲自然語言處理。它是一個簡單的解析問題。 – Identity1