合并两个单词列表
Merge two wordlists
我想将两个单词表合并到一个文件中。必须删除所有重复项。每个单词用换行符分隔。我找过这种程序,但什么也找不到。我在寻找正确的东西吗?是否有此功能的c/c++实现?
// read input
std::ifstream in( file_path );
typedef std::set< std::string > wordlist_type;
wordlist_type wordlist;
std::string word;
while ( in >> word ) {
wordlist.insert( word );
}
// repeat with other files to merge more wordlists
// now output to a new file
std::ofstream out( output_path );
for ( wordlist_type::iterator it = wordlist.begin(); it != wordlist.end(); ++ it ) {
out << * it << 'n';
}
文件有多大。如果你能把它们都记在记忆里,使用STL:比较简单
std::vector<std::string> v(
(std::istream_iterator<std::string>( ifile1 )),
(std::istream_iterator<std::string>()));
v.insert(v.end(),
std::istream_iterator<std::string>( ifile2 ),
std::istream_iterator<std::string>());
std::sort( v.begin(), v.end() );
std::copy( v.begin(), std::unique( v.begin(), v.end() ),
std::ostream_iterator<std::string>( ofile, "n" ) );
或
std::vector<std::string> v1(
(std::istream_iterator<std::string>( ifile1 )),
(std::istream_iterator<std::string>()) );
std::sort( v1.begin(), v1.end() );
v1.erase( std::unique( v1.begin(), v1.end() ), v1.end() );
std::vector<std::string> v2(
(std::istream_iterator<std::string>( ifile2 )),
(std::istream_iterator<std::string>()) );
std::sort( v2.begin(), v2.end() );
v2.erase( std::unique( v2.begin(), v2.end() ), v2.end() );
std::set_intersection( v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::ostream_iterator<std::string>( ofile, "n" ) );
如果它们不适合记忆,你可能需要对它们进行排序文件(使用system
调用本地实用程序(,然后执行手动合并:
class FilterDuplicates
{
std::ostream& myDest;
std::string myLastOutput;
public:
Outputter( std::ostream& dest ) : myDest( dest ) {}
void write( std::string const& word ) const
{
if ( word != myLastOutput ) {
myDest << word;
myLastOutput = word;
}
}
};
ifile1 >> s1;
ifile2 >> s2;
FilterDuplicates out( ofile )
while ( ifile1 && ifile2 ) {
if ( s1 < s2 ) {
out.write( s1 );
ifile1 >> s1;
} else {
out.write( s2 );
ifile2 >> s2;
}
}
while ( ifile1 ) {
out.write( s1 );
ifile1 >> s1;
}
while ( ifile2 ) {
out.write( s2 );
ifile2 >> s2;
}
#include <string>
#include <set>
#include <iostream>
int main()
{
std::set<std::string> s;
std::string word;
while (std::cin >> word)
s.insert(s);
for (std::set<std::string>::const_iterator i = s.begin(); i != s.end(); ++i)
std::cout << s << 'n';
}
用法:
cat input1 input2 | program > output
类似的东西。。。
std::set<std::string> words;
std::string word;
while(cin >> word)
if (words.insert(word).second)
cout << word;
编辑:哎呀,太急于简化了。。。
如果您可以访问unix
cat file1 file2 | sort | uniq > file3
相关文章:
- 如何阅读两个单词,然后阅读C++中的一行?
- 用c++交换短语中单词的前两个字母
- 从文件 (C++) 输入两个单词字符串
- 通过单词列表将两个字符串移动以比较每个单词
- 如何在两个单词之间添加空格
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词
- 从C 中的两个字符串中找到唯一的常见单词
- 如何使用C 中的Regex在给定句子中的多个空格隔开的两个单词匹配
- 从两个单词之间获取字符串
- 从文件中阅读句子,并将每个句子分成两个单词短语
- C++ 计算文件中两个单词之间的单词
- C++如何在两个单词之间获取字符串/字符
- 提取两个单词之间的域
- 将用户输入的前两个单词分隔一个空格,然后存储剩余短语(C++)
- 将两个单词读入一个char数组元素
- c++将文本文件中的两个单词读取到单个字符数组中
- 是否有可能在某个表达式中定义两个单词,而不仅仅是一个单词
- 将用户输入拆分为向量中的两个单词
- 将每行两个单词的文件读入两个不同的向量
- 合并两个单词列表