我有下面的代碼打印每一個獨特的字,從一個文本文件的數量(包含> = 30K字),但它是由空格隔開的話,我就喜歡這樣的結果:C++指定分隔從文本文件中讀取單詞
如何修改代碼以指定預期的分隔符?
template <class KTy, class Ty>
void PrintMap(map<KTy, Ty> map)
{
typedef std::map<KTy, Ty>::iterator iterator;
for (iterator p = map.begin(); p != map.end(); p++)
cout << p->first << ": " << p->second << endl;
}
void UniqueWords(string fileName) {
// Will store the word and count.
map<string, unsigned int> wordsCount;
// Begin reading from file:
ifstream fileStream(fileName);
// Check if we've opened the file (as we should have).
if (fileStream.is_open())
while (fileStream.good())
{
// Store the next word in the file in a local variable.
string word;
fileStream >> word;
//Look if it's already there.
if (wordsCount.find(word) == wordsCount.end()) // Then we've encountered the word for a first time.
wordsCount[word] = 1; // Initialize it to 1.
else // Then we've already seen it before..
wordsCount[word]++; // Just increment it.
}
else // We couldn't open the file. Report the error in the error stream.
{
cerr << "Couldn't open the file." << endl;
}
// Print the words map.
PrintMap(wordsCount);
}
並不清楚你的要求。 – OldProgrammer
只是要說清楚:你想把「你」算作「你」,「你!」作爲「你」等?是這樣嗎? – Paulo
@OldProgrammer這段代碼打印每個唯一字的頻率,但它的計算方式是空白,它正在考慮'you'和你''因爲不同的詞 –