《笑傲江湖》是金庸的重要武侠作品之一。这里给出一个《笑傲江湖》的网络版本,
文件名为“笑傲江湖-网络版.txt”。
问题1:请编写程序,统计该文件中出现的所有中文字符及标点符号的数量,每个字符及数量之间用冒号:分隔,
例如“笑:1024”,将所有字符及数量的对应采用逗号分隔,以CSV文件格式保存到“笑傲江湖-字符统计.txt”文件中。
注意,统计字符不包括空格和回车。
问题2:请编写程序,统计“笑傲江湖-网络版.txt”中出现在引号内所有字符占文本总字符的比例,
采用如下方式打印输出:
用程序运行结果的真实数字替换上述示例中数字,均保留整数,字符串中标点符号采用中文字符。
输出格式
问题一输出:
笑:1024, 傲:2048, 江:128, 湖:64
(略)
问题二输出:
占总字符比例:20%。
问题1参看代码
fi = open("笑傲江湖-网络版.txt", "r", encoding='utf-8')
fo = open("笑傲江湖-字符统计.txt", "w", encoding='utf-8')
txt = fi.read()
d = {}
for c in txt:
d[c] = d.get(c, 0) + 1
del d[' ']
del d['\n']
ls = []
for key in d:
ls.append("{}:{}".format(key, d[key]))
fo.write(",".join(ls))
fi.close()
fo.close()
问题2参考代码
fi = open("笑傲江湖-网络版.txt", "r", encoding='utf-8')
txt = fi.read()
cnt = 0
flag = False
for c in txt:
if c == "“":
flag = True
continue
if c == "”":
flag = False
if flag:
cnt += 1
print("占总字符比例:{:.0%}。".format(cnt/len(txt)))
fi.close()
《射雕英雄传》是金庸的重要武侠作品之一。这里给出一个《射雕英雄传》的网络版本,
文件名为“射雕英雄传-网络版.txt”。
请编写程序,统计该文件出现的所有中文词语及出现次数(不要求输出),
并输出按照出现次数最多的8个词语,采用如下方式打印输出。
《射雕英雄传》下载
输出格式
词语1,词语2,词语3,词语4,词语5,词语6,词语7,词语8
参考代码
import jieba
fi = open("射雕英雄传-网络版.txt", "r", encoding='utf-8')
txt = fi.read()
fi.close()
ls = jieba.lcut(txt)
d = {}
for w in ls:
d[w] = d.get(w, 0) + 1
for x in " \n,。!“”:":
del d[x]
rst = []
for i in range(8):
mx = 0
mxj = 0
for j in d:
if d[j] > mx:
mx = d[j]
mxj = j
rst.append(mxj)
del d[mxj]
print(",".join(rst))
《侠客行》是金庸的重要武侠作品之一,主要叙述一个懵懂少年石破天的江湖经历。
这里给出一个《侠客行》的网络版本,文件名为“侠客行-网络版.txt”。
基础中文字符的Unicode编码范围是[0x4e00,0x9fa5],请统计给定文本中存在多少该范围内的
基础中文字符以及每个字符的出现次数。以如下模式(CSV格式)保存在“侠客行-字符统计.txt”文件中。
示例输出中括号内是对应字符的十六进制Unicode编码形式,冒号后是出现次数,逗号两侧无空格。
输出格式
侠(0x4fa0):888, 客(0x5ba2):666, 行(0x884c):111
(略)
参考代码
fi = open("侠客行-网络版.txt", "r", encoding='utf-8')
fo = open("侠客行-字符统计.txt", "w", encoding='utf-8')
txt = fi.read()
d = {}
for c in txt:
if 0x4e00 <= ord(c) <= 0x9fa5:
d[c] = d.get(c, 0) + 1
ls = []
for key in d:
ls.append("{}(0x{:x}):{}".format(key, ord(key),d[key]))
fo.write(",".join(ls))
fi.close()
fo.close()
文件 sweb.html 保存了一个网页的源代码,其中,“href=”引导后面会有一个URL链接,
例如:href="http://news.sina.com.cn/feedback/post.html",其中,
有一种链接前后都有空格,且双引号内以“http://”开头。
请编写程序,解析这个文件,提取出现符合上述特征的URL链接,每个链接一行,保存到“text-urls.txt”文件中,
格式如下:
输出格式
URL1
URL2
(略)
参考代码
fi = open("sweb.html", "r", encoding='utf-8')
fo = open("text-urls.txt", "w", encoding='utf-8')
txt = fi.read()
ls = txt.split(" ")
urls = []
for item in ls:
if item[:5]=="href=" and item[6:13]=="http://":
x = item.find(">",5)
if x == -1:
urls.append(item[6:-1])
else:
urls.append(item[6:x-len(item)-1])
for item in urls:
fo.write(item +"\n")
fi.close()
fo.close()