Textractor_test/extensions/removerepeatphrase2.cpp

53 lines
1.8 KiB
C++
Raw Permalink Normal View History

2019-08-08 02:05:50 +08:00
#include "extension.h"
bool ProcessSentence(std::wstring& sentence, SentenceInfo sentenceInfo)
{
if (sentenceInfo["text number"] == 0) return false;
2019-08-10 10:11:34 +08:00
// This algorithm looks at all the prefixes of the sentence: if a prefix is found later in the sentence, it is removed from the beginning and the process is repeated
auto timeout = GetTickCount64() + 30'000; // give up if taking over 30 seconds
2019-08-08 02:05:50 +08:00
auto data = std::make_unique<wchar_t[]>(sentence.size() + 1);
wcscpy_s(data.get(), sentence.size() + 1, sentence.c_str());
wchar_t* dataEnd = data.get() + sentence.size();
int skip = 0, count = 0;
for (wchar_t* end = dataEnd; end - data.get() > skip && GetTickCount64() < timeout; --end)
2019-08-08 02:05:50 +08:00
{
std::swap(*end, *dataEnd);
int junkLength = end - data.get() - skip;
auto junkFound = wcsstr(sentence.c_str() + skip + junkLength, data.get() + skip);
std::swap(*end, *dataEnd);
if (junkFound)
{
if (count && junkLength < min(skip / count, 4)) break;
skip += junkLength;
count += 1;
end = dataEnd;
}
}
if (count && skip / count >= 3)
{
sentence = data.get() + skip;
return true;
}
return false;
}
TEST(
{
2019-10-02 17:30:14 +08:00
InfoForExtension nonConsole[] = { { "text number", 1 }, {} };
2019-08-08 02:05:50 +08:00
std::wstring cyclicRepeats = L"_abcde_abcdef_abcdefg_abcdefg_abcdefg_abcdefg_abcdefg";
std::wstring buildupRepeats = L"__a_ab_abc_abcd_abcde_abcdef_abcdefg";
2019-10-02 17:30:14 +08:00
ProcessSentence(cyclicRepeats, { nonConsole });
ProcessSentence(buildupRepeats, { nonConsole });
2019-08-08 02:05:50 +08:00
assert(cyclicRepeats == L"_abcdefg");
assert(buildupRepeats == L"_abcdefg");
std::wstring empty = L"", one = L" ", normal = L"This is a normal sentence. はい";
2019-10-02 17:30:14 +08:00
ProcessSentence(empty, { nonConsole });
ProcessSentence(one, { nonConsole });
ProcessSentence(normal, { nonConsole });
2019-08-08 02:05:50 +08:00
assert(empty == L"" && one == L" " && normal == L"This is a normal sentence. はい");
}
);