gpt4 book ai didi

c++ - 逐字逐句阅读长文本

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:13 24 4
gpt4 key购买 nike

我正在尝试阅读一段很长的文本,并将这段文本分成它包含的每个单词。我所做的第一次尝试是使用 std::ifstreamoperator>> 从文件中读取它以读入字符串。问题是,因为它只剪切空白字符上的文本,所以我仍然在短语的最后一个单词处得到句点(如 problem.)和一些不代表什么的特殊字符串(有时我有->**).

我考虑过逐个读取一个字符,或者将读取的字符串也拆分成一个字符,并发现删除了不在正确范围内的字符(介于 a-z、A-Z 和 0-9 之间),但这个解决方案似乎非常困惑。另外,我无法使用正则表达式,因为我使用的是 GCC 4.8.3,而且无法使用 Boost。

是否有比第二个更好的解决方案,或者这是好的方法?我所说的好是指相对容易实现并产生预期结果(仅字母数字字符)。

最佳答案

您可以在您的流语言环境中安装自定义 ctype:

#include <iostream>
#include <locale>
#include <sstream>

class WordCharacterClassification : public std::ctype<char>
{
private:
typedef std::ctype<char> Base;
const mask* initialize_table(const Base&);

public:
typedef Base::mask mask;
typedef Base::char_type char_type;

public:
WordCharacterClassification(const Base& source, std::size_t refs = 0)
: Base(initialize_table(source), false, refs)
{}


private:
mask m_table[Base::table_size];
};

inline const typename WordCharacterClassification::mask*
WordCharacterClassification::initialize_table(const Base& source) {
const mask* src = source.table();
const mask* src_end = src + Base::table_size;
const mask space
= std::ctype_base::space
| std::ctype_base::cntrl
| std::ctype_base::digit
| std::ctype_base::punct;

mask* dst = m_table;
for( ; src < src_end; ++dst, ++src) {
*dst = *src;
if(*src & space)
*dst |= std::ctype_base::space;
}
return m_table;
}


int main() {
std::istringstream in("This->is a delimiter-test4words");
std::locale locale = in.getloc();

WordCharacterClassification classification(
std::use_facet<std::ctype<char>>(locale),
// We hold a reference and do not transfer ownership:
true);

in.imbue(std::locale(locale, &classification));

std::string word;
std::cout << "Words:\n";
while(in >> word) {
std::cout << word << '\n';
}
}

注意:静态表(不复制原始表)会简化它。

关于c++ - 逐字逐句阅读长文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24683076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com