求c#程序:一个文件中,把每一个单词都分割出来,并统计单词的总数和每个单词出现的次数,并将这些单词排序

求c#程序:一个文件中,把每一个单词都分割出来,并统计单词的总数和每个单词出现的次数,并将这些单词排序,第1张

1L写的不对,他要求的是单词,不是字符

//调用

Stats("hello,nice to meet you,hello,i say good bye to you")

//函数创建

protected void Stats(String article)

{

MatchCollection mc = Regex.Matches(article, @"\b\w+\b")

Response.Write("总数:"+mc.Count+"<br/>")

Dictionary<String, int>dct = new Dictionary<String, int>(mc.Count)

foreach(Match mt in mc)

{

if (dct.ContainsKey(mt.Value))

{

dct[mt.Value]++

}

else

{

dct.Add(mt.Value,1)

}

}

dct = dct.OrderBy(i =>i.Key).ToDictionary(c =>c.Key, c =>c.Value)

//输出结果

foreach (KeyValuePair<String,int>de in dct)

{

Response.Write(de.Key+":"+de.Value+"<br/>")

//换成Writeline输出,如果是WinForm

}

}

----------结果------------

总数:12

bye:1

good:1

hello:2

i:1

meet:1

nice:1

say:1

to:2

you:2

-------------------------------

很清晰了吧,难道读文件跟显示都不会?

-------------------------------

作业的话自己做吧,我只负责解决问题

#include"stdio.h"

#include"string.h"

void RevStr(char str[])

{

int i=0,k=0

int IsNewWord=0

char wordtmp[50] /*存储单词*/

char strnew[500]/*新句子*/

strnew[0]='\0'

wordtmp[0]='\0'/*清空字符串*/

for(i=strlen(str)-1i>=0i--)

{

if(((str[i]>='a')&&(str[i]<='z'))||((str[i]>='A')&&(str[i]<='Z'))) /*找到新单词*/

{

IsNewWord=1

wordtmp[k]=str[i]

wordtmp[k+1]='\0'

k++

}

else

{

strcat(strnew,strrev(wordtmp))/*单词翻转后连接到新句子*/

k=0

IsNewWord=0

wordtmp[k]=str[i]

wordtmp[k+1]='\0'

k=0

strcat(strnew,strrev(wordtmp))/*标点符号和空格也连接到新句子*/

}

}

strcat(strnew,strrev(wordtmp))/*最后找到的句子的第一个单词连接到新句子最后*/

puts(strnew)

}

void main()

{

char str[500]

printf("Please input:")

gets(str)

RevStr(str)

}

>>> astring = 'Hello'

# 最直接的方法

>>> alist = list(astring)

>>> alist

['H', 'e', 'l', 'l', 'o']

# 列表推导

>>> alist = [ch for ch in astring]

>>> alist

['H', 'e', 'l', 'l', 'o']

# 循环法

>>> alist = []

>>> for ch in astring:

...     alist.append(ch)

... 

>>> alist

['H', 'e', 'l', 'l', 'o']


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11840034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存