首页 > 试题广场 >

关键词

[编程题]关键词
  • 热度指数:3367 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
小易今天读了一篇英语文章,他现在想从里面找出一个单词作为这篇文章的关键词,一个单词可以作为关键词当且仅当它在这篇文章中出现的频率不低于 1% ,现在他想知道有多少个不同的单词可以作为关键词。
一个单词出现的频率%

  

输入描述:
第一行一个正整数 n,代表这篇文章的单词总数。
接下来 n 行每行一个字符串,代表一个单词,单词仅由大小写英文字母组成。
1<= n <= 106
保证所有的字符串长度之和不超过 106


输出描述:
仅一行一个整数表示答案。
示例1

输入

5
I
I
am
a
boy

输出

4

说明

单词 I  出现的频率为 40% ,其他单词出现的频率均为 20%。所以都可以作为关键词。
非常简单,直接统计词频,然后看哪些词的词频达到了关键词的标准即可
n = int(input())
wc = dict()
for _ in range(n):
    word = input().strip()
    if word not in wc:
        wc[word] = 1
    else:
        wc[word] += 1
count = 0
for w in wc:
    if wc[w] / n >= 0.01:
        count += 1
print(count)


发表于 2021-01-17 23:12:17 回复(3)
class num_nn(): def __init__(self): self.num_n = [] self.count_m = 0  def play(self): self.n = input("请输入单词数: ") for i in range(0,int(self.n)):
            num = input("请输入单词: ") self.num_n.append(num) self.num_n_set = set(self.num_n) for item in self.num_n_set: print("the %s has found %s" %(item,self.num_n.count(item))) if int(self.num_n.count(item))/int(self.n) >= 0.01: self.count_m = self.count_m + 1  print(self.count_m) if __name__ == '__main__':
    numnn = num_nn()
    numnn.play()
发表于 2021-02-28 15:14:28 回复(0)
import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        HashMap<String,Integer> hm=new HashMap<String,Integer>();
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        sc.nextLine();
        int res=0;
        for(int i=0;i<n;i++){
            String tmp=sc.nextLine();
            if(hm.get(tmp)==null){
                hm.put(tmp,1);
            }else{
                hm.put(tmp,hm.get(tmp)+1);
            }
        }
        for(String key:hm.keySet()){
            if((hm.get(key)*100)>=n){
                res++;
            }
        }
        System.out.println(res);
    }
}

发表于 2021-01-21 00:16:25 回复(2)
翻了一遍回答发现没有JavaScript的解题思路,那我来发一下吧,如果有可以优化的地方,欢迎指出

#JavaScript
var arr=new Array();    //构造数组
while(line=readline()){ //将第一行的总字数,和后面每一行的
   arr.push(line);      //单词作为元素加入数组
}
var nuum= arr[0];       //初始化总词数
var key=0;              //初始化关键词数
var times=nuum*0.01;    //计算作为关键词的最低频率
for(let u = 1;u<=nuum;u++){//循环每个单词
    var word = 0;          //初始化重复单词数
    if(arr.indexOf(arr[u])==u){//如果该单词重复出现则跳过该单词
        for(let j=1;j<=nuum;j++){//循环遍历数组
            if(arr[u]==arr[j]){
                word++;          //计算该词重复单词数
                if(word>=times){//判断该单词是否为关键词
                    key++;       
                    break;      //代码优化,判断为关键词时立刻跳出本次循环
                }
            }
        }
    }
}
print(key)



发表于 2021-11-03 21:43:26 回复(2)

python处理数据真的很容易

n=eval(input())
word_list = []
word_count =[]
for i in range(n):
    word=input()
    if word in word_list:
        word_count[word_list.index(word)]+=1
    else:
        word_list.append(word)
        word_count.append(1)
word_frequency=list(map(lambda x:(1 if x/n>=0.01 else 0),word_count))
print(sum(word_frequency))
发表于 2022-04-02 15:06:37 回复(0)

#include<iostream>

#include<map>

using namespace std;

int main()

{

    map<string, int> m;

    int ans = 0, n, total;

    cin>>n;

    total = n;

    while(n--)

    {


        string s;

        cin>>s;

        m[s]++;

    }

    for (auto i = m.begin(); i != m.end(); i++)

    {

        double tempInt = i->second;

        double percent = tempInt/total;

        if (percent - 0.01 >= 0)

            ans++;

    }

    cout<<ans<<endl;

    return 0;

}

发表于 2022-02-27 12:11:41 回复(0)
dict_1 = {}
list_1 = []
count = 0
num = int(input("请输入单词个数:"))
for i in range(1,num):
    list_1.append(input("请输入单词:"))
    i += 1
for key in list_1:
    if dict_1.get(key) == None:
        dict_1[key] = 1
    else:
        dict_1[key] += 1
dict_2 = dict(sorted(dict_1.items(),key=lambda x:x[1],reverse=True))
for value in dict_2.values():
    if value/num > 0.01:
        count += 1
print(count)
发表于 2022-02-23 14:09:23 回复(0)
请问c++代码,统计词频时使用小数相除为什么只能通过部分测试用例?
// 情况1:使用整数相除
if(n / ((*iter).second) <= 100){
    m++;
}
// 情况2:使用小数相除
if((float)((*iter).second) / (float)n >= 0.01){
    m++;
}

发表于 2021-09-13 17:01:47 回复(0)
#include<bits/stdc++.h>
using namespace std;
map<string, int> m;
char s[int(1e6)];
int main()
{
    int ans = 0, n, t;
    scanf("%d", &n);
    t = n;
    while(n--)
    {

        scanf("%s", s);
        m[string(s)]++;
    }
    t = t*0.1;
    for (auto i = m.begin(); i != m.end(); i++)
    {
        if (i->second >= t) ans++;
    }
    printf("%d", ans);
    return 0;
}

发表于 2021-01-14 21:21:38 回复(1)
大佬们看一下哪里不对,谢谢各位大佬了。
'''

while True:
    try:
        n=int(input())
        for i in range(n):
            a[i]=input()
        m=len(a)
        c=list(set(a))
        for i in a:
            d=' '.join(i)
        for i in range(len(c)):
            for j in c:
                e[i]=d.count(j)
                if e[i]/m>=0.01:
                    b.append(e[i])
        print(len(b))
    except:
        break
'''

发表于 2023-01-17 15:57:51 回复(0)
const count = parseInt(readline())
const dic = {}
for(let i =0;i<count;i++){
    let temp = readline()
    if(dic[temp]) dic[temp]++
    else dic[temp] = 1
}
let answer = 0
Object.keys(dic).forEach(item=>{
    if (Math.floor(dic[item]/count*100)) answer++
})
console.log(answer)
利用了字典的特性
发表于 2022-10-25 00:17:26 回复(0)
while True:
    try:
        n = int(input())
        a = []
        for i in range(n):
            a.append(str(input()))
        hashmap = {}
        for i in set(a):
            hashmap[i] = int(a.count(i))
        count = 0
        for i,v in hashmap.items():
            if int(v) / n > 0.01:
                count += 1
        print(count)
    except:
        break
但是有3个用例跑不过,不知道有啥问题
发表于 2022-07-25 19:08:30 回复(0)
统计词频,判断是否达到标准即可
n = int(input().strip())
words = [input().strip() for _ in range(n)]
count={}
for word in words:
    count[word] = count.get(word,0)+1
nums = 0
for word in count.keys():
    if count[word] >= n*0.01:
        nums+=1
print(nums)
发表于 2022-04-27 11:58:43 回复(0)
n=int(input().strip())
A=[]
for i in range(n):
    A.append(input().strip())
uA=[]
for i in range(len(A)):
    if A[i] not in uA:
        uA.append(A[i])
c=0
for i in range(len(uA)):
    if A.count(uA[i])/len(A)>=0.01:
        c+=1
print(c) 

发表于 2021-05-26 20:25:41 回复(0)
using System;

internal class Program
{
    private static void Main(string[] args)
    {
        int number = int.Parse(Console.ReadLine());
        int targetALL = 0;
        string[] eng = new string[number];
        for (int i = 0; i < number; i++)
        {
            String curr = Console.ReadLine();
            eng[i] = curr;
        }

        string[] checkEng = new string[number];//检测过频率的放入
        for (int i = 0, j = 0; i < number; i++)
        {
            bool isRepeat = ISRepeat(eng[i], checkEng);//检测当前对象是否已经判断过

            if (!isRepeat)
            {
                float num = Check(eng[i], eng);
                if (num >= 0.1)
                {
                    targetALL++;
                }
                checkEng[j] = eng[i];
                j++;//判断过频率的放入checkEng中,避免重复判断
            }
            else
            {
                continue;
            }
        }
        Console.WriteLine(targetALL);
    }

    private static float Check(string target, string[] str)
    {//判断指定字符在字符串**现的概率
        int number = 0;
        for (int i = 0; i <= str.Length - 1; i++)
        {
            if (str[i] == target)
            {
                number++;//
            }
        }
        float allNumber = str.Length;
        float retu = (float)((number) / (allNumber));//todo 最好同类型相加减乘除,否则可能发生隐式转换 丢失精度
        return retu;//
    }

    private static bool ISRepeat(string target, string[] str)
    {//判断指定字符在字符串**是否重复
        for (int i = 0; i <= str.Length - 1; i++)
        {
            if (str[i] == target)
            {
                return true;
            }
        }
        return false;
    }
}

思路如图:两个函数一个判断是否重复,避免重复判断,一个进行频率检测,如果大于0.1频率,则最终数字++,
问题是在数据小没问题,数据量大(1000)出现输出0错误,求解 case通过60%,出现输出0错误

发表于 2021-04-15 16:38:30 回复(0)
classtitle:
    defistitle(self,lists):
        list1=lists.split()
        dict1=dict()
        sum=0
        forch inlist1:
            dict1[ch]=dict1.get(ch,0)+1
        forkeys,values indict1.items():
            if1<values<9:
                continue
            elifvalues/len(list1)>=0.01:
                sum=sum+1
        returnsum
 
t=title()
print(t.istitle('k k l o i u y t r e w q p l m n b v c x d y u i o 1 1 1 2 3 3 4 5 4 4 '))
发表于 2021-04-07 21:40:37 回复(0)
n=int(input('请输入该文章所含单词数:'))
qty=0 #关键词个数 t=() #这里一定要用不可变对象,列表是可变的,如果用列表的话,lst2改变,t这里的元素也会变 for i in range(n):
a=input('请输入文中的单词:')
t+=(a,) #元组的增加 lst2=[] for y in t:
    lst2.append(y) #将元组中的元素赋给列表 print(t,id(t),type(t)) print(lst2,id(lst2),type(lst2)) for s1 in lst2: #遍历列表中的元素  m=lst2.count(s1) if m > 1:
        lst2.remove(s1) #删除相同的元素,只留一个,最终lst2中只含有不同的元素  continue  else: continue print('删减后的lst2:',lst2) for j in lst2: #遍历lst2,即所有不同的单词全部计算一遍  h = t.count(j) #得出该单词在含相同元素的元组中,所占的个数  print(j,'出现的次数为',h,end='')
    x=h/n print('其占比为',x) if x>=0.01:
        qty+=1  continue  else: continue print('总共有{0}个单词可作为关键词'.format(qty))

编辑于 2021-03-30 22:42:15 回复(0)
# Python3
n = int(input())
w = {}
for i in range(n):
    word = input().strip()
    if word not in w:
        w[word]=1
    else:
        w[word]+=1
count = 0
for word in w:
    if w[word]/n>=0.01:
        count+=1
print(count)

发表于 2021-03-22 16:33:23 回复(0)
import java.io.*;
import java.util.HashMap;
public class Main{
    public static void main(String[] args) throws IOException{
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(reader.readLine());
        HashMap<String,Integer> map = new HashMap<>();
        String str;
        for(int i = 0;i < n;i++){
            str = reader.readLine();
            map.put(str,map.getOrDefault(str,0) + 1);
        }
        double a = 0.01*n;
        int res = 0;
        for(int num : map.values()){
            if(num  >= a) res++;
        }
        System.out.println(res);
    }
   
}

发表于 2021-02-19 18:10:24 回复(0)
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
public class Main{
   public static void main(String[] args)
   {
    int n=0;
    Scanner scan = new Scanner(System.in);
    /*next()不会吸取字符前/后的空格/Tab键,只吸取字符,
     开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取*/
    /*nextLine()吸取字符前后的空格/Tab键,回车键截止。*/
    /*也可以写成:
                   n = scan.nextInt();
                   scan.nextLine();
    即把第一行读取int类型后的回车符吸取掉,要不然nextLine第一次读取直接读取为“”*/
    String s = scan.nextLine();
    n = Integer.parseInt(s);
    String[] a = new String[n];
    for(int i=0;i<a.length;i++)
    {
         a[i]=scan.nextLine();
    }
       //调用count函数,计算并输出关键值的个数:
      System.out.println(count(a));
      scan.close();
   }
    //计算关键值的个数
   private static int count(String[] arg)
   {
       int k=arg.length;
       int c=0;
       HashMap<String,Integer> stringMap = new HashMap<String,Integer>();
       for(int i = 0; i<k; i++)
       {
          /*另一种写法,一次循环遍历,用时更少:
          if(map.get(arg[i])==null)
          {
              map.put(arg[i],1);
          }
          else
          {
              map.put(arg[i],map.get(arg[i])+1);
          }*/
          if (stringMap.get(arg[i])==null)
          {
                int m=1;
                for(int j=i+1;j<k;j++)
                {
                    /*这里引用数据类型“equals”用来比较两个值的内容是否相等,
                    “==”用来比较地址是否相等,刚一开始给我带来很大困扰 */
                    if(arg[i].equals(arg[j]))
                    {
                        m++;
                    }
                }
                stringMap.put(arg[i],m);
           }
        }
       //读取hashmap的value值,应该还有别的方法,希望能留下评论,继续探讨
       Set<Map.Entry<String,Integer>> entries = stringMap.entrySet();
       for(Map.Entry<String,Integer> entry: entries)
       {
           if(entry.getValue()*100>=k)
           {
               c++;
           }
       }
       return c;
   }
}

发表于 2021-02-14 11:03:16 回复(0)