计算文件中每个单词出现的次数

如何解决计算文件中每个单词出现的次数

| 嗨,我正在编写一个程序,该程序计算每个单词在文件中出现的次数。然后,它会打印一个计数在800到1000之间的单词列表,按计数顺序排序。我坚持要保持计数器,以查看第一个单词是否与下一个单词匹配,直到出现新单词为止。我主要尝试打开文件,逐个单词读取每个单词,然后在while循环中调用sort来对向量进行排序。然后,在for循环中遍历所有单词,如果第一个单词等于第二个++。我不认为这是您保持反击的方式。 这是代码:
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

vector<string> lines;
vector<int> second;
set<string> words;
multiset<string> multiwords;

void readLines(const char *filename)
{
    string line;
    ifstream infile;
    infile.open(filename);
    if (!infile)
    {       
        cerr << filename << \" cannot open\" << endl; 
          return; 
    }       
    getline(infile,line);
    while (!infile.eof())
    {
        lines.push_back(line);
        getline(infile,line);
    }  
    infile.close();
}

int binary_search(vector<string> &v,int size,int value)
{
    int from = 0;
    int to = size - 1;
    while (from <= to)
    {  
        int mid = (from + to) / 2;
        int mid_count = multiwords.count(v[mid]);
        if (value == mid_count) 
            return mid;
        if (value < mid_count) to = mid - 1;
        else from = mid + 1;
    }
   return from;
}

int main() 
{
    vector<string> words;
    string x;
    ifstream inFile;
    int count = 0;

    inFile.open(\"bible.txt\");
    if (!inFile) 
    {
        cout << \"Unable to open file\";
        exit(1);
    }
    while (inFile >> x){
        sort(words.begin(),words.end());
    }

    for(int i = 0;i < second.size();i++)
    {
        if(x == x+1)
        {
            count++;
        }
        else
            return;
    }
    inFile.close();
}
    

解决方法

一种解决方案可能是:定义
letter_only
语言环境,以便忽略来自流的标点符号,并仅从输入流中读取有效的“英语”字母。这样,流将把\“ ways \”,\“ ways。\”和\“ ways!\”视为相同的单词\“ ways \”,因为流将忽略像\“这样的标点符号。 “和\”!\“。
struct letter_only: std::ctype<char> 
{
    letter_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc[\'A\'],&rc[\'z\'+1],std::ctype_base::alpha);
        return &rc[0];
    }
};
然后将其用作:
int main()
{
     std::map<std::string,int> wordCount;
     ifstream input;

     //enable reading only english letters only!
     input.imbue(std::locale(std::locale(),new letter_only())); 

     input.open(\"filename.txt\");
     std::string word;
     std::string uppercase_word;
     while(input >> word)
     {
         std::transform(word.begin(),word.end(),std::back_inserter(uppercase_word),(int(&)(int))std::toupper); //the cast is needed!
         ++wordCount[uppercase_word];
     }
     for (std::map<std::string,int>::iterator it = wordCount.begin(); 
                                               it != wordCount.end(); 
                                               ++it)
     {
           std::cout << \"word = \"<< it->first 
                     <<\" : count = \"<< it->second << std::endl;
     }
}
    ,他。我知道直截了当地显示解决方案并没有真正帮助您。然而。 我浏览了一下您的代码,发现许多未使用和混乱的位。这是我要做的:
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <vector>

using namespace std;

// types
typedef std::pair<string,size_t> frequency_t;
typedef std::vector<frequency_t> words_t;

// predicates
static bool byDescendingFrequency(const frequency_t& a,const frequency_t& b)
{ return a.second > b.second; }

const struct isGTE // greater than or equal
{ 
    size_t inclusive_threshold;
    bool operator()(const frequency_t& record) const 
        { return record.second >= inclusive_threshold; }
} over1000 = { 1001 },over800  = { 800 };

int main() 
{
    words_t words;
    {
        map<string,size_t> tally;

        ifstream inFile(\"bible.txt\");
        string s;
        while (inFile >> s)
            tally[s]++;

        remove_copy_if(tally.begin(),tally.end(),back_inserter(words),over1000);
    }

    words_t::iterator begin = words.begin(),end = partition(begin,words.end(),over800);
    std::sort(begin,end,&byDescendingFrequency);

    for (words_t::const_iterator it=begin; it!=end; it++)
        cout << it->second << \"\\t\" << it->first << endl;
}
授权版本:
993 because
981 men
967 day
954 over
953 God,910 she
895 among
894 these
886 did
873 put
868 thine
864 hand
853 great
847 sons
846 brought
845 down
819 you,811 so
伏尔加塔:
995 tuum
993 filius
993 nec
966 suum
949 meum
930 sum
919 suis
907 contra
902 dicens
879 tui
872 quid
865 Domine
863 Hierusalem
859 suam
839 suo
835 ipse
825 omnis
811 erant
802 se
两个文件的性能大约为1.12s,但是在将
map<>
替换为ѭ8after之后,只有0.355s。     ,可以通过出现一次
map< string,int >
,逐个读取单词,并在
m[ word ]
中增加计数器来完成更有效的方法。在考虑完所有单词之后,遍历地图,对于给定范围内的单词,将它们添加到
multimap<int,string>
中。最后转储多图的内容,该内容将按出现次数和字母顺序排序...     ,只是为了好玩,我使用Boost MultiIndex以c ++ 0x风格做了一个解决方案。 没有
auto
关键字(类型推断),此样式将非常笨拙。 通过始终按单词和按频率维护索引,无需删除,分区或对单词列表进行排序:它会一直存在。 要编译并运行:
g++ --std=c++0x -O3 test.cpp -o test
curl ftp://ftp.funet.fi/pub/doc/bible/texts/english/av.tar.gz |
    tar xzO | sed \'s/^[ 0-9:]\\+//\' > bible.txt
time ./test
#include <boost/foreach.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

struct entry 
{
    string word;
    size_t freq;
    void increment() { freq++; }
};

struct byword {}; // TAG
struct byfreq {}; // TAG

int main() 
{
    using ::boost::lambda::_1;
    using namespace ::boost::multi_index;
    multi_index_container<entry,indexed_by< // sequenced<>,ordered_unique    <tag<byword>,member<entry,string,&entry::word> >,// alphabetically
            ordered_non_unique<tag<byfreq>,size_t,&entry::freq> > // by frequency
                > > tally;

    ifstream inFile(\"bible.txt\");
    string s;
    while (inFile>>s)
    {
        auto& lookup = tally.get<byword>();
        auto it = lookup.find(s);

        if (lookup.end() != it)
            lookup.modify(it,boost::bind(&entry::increment,_1));
        else
            lookup.insert({s,1});
    }

    BOOST_FOREACH(auto e,tally.get<byfreq>().range(800 <= _1,_1 <= 1000))
        cout << e.freq << \"\\t\" << e.word << endl;

}
注意如何 定义自定义
entry
类型而不是使用
std::pair
变得更加方便 (出于明显的原因),这比我之前的代码要慢:这在插入阶段按频率维护索引。这是不必要的,但是它可以更有效地提取[800,1000]范围:
tally.get<byfreq>().range(800 <= _1,_1 <= 1000)
已经订购了多组频率。因此,的实际速度/内存交易可能会偏向于此版本,特别是在文档较大且包含很少重复单词的情况下(尤其是,这是众所周知的属性,不适合圣经的语料库文本使用,以免受到干扰)有人将其翻译为新泻。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-