在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件: open(文件名,访问模式)
结果
hello world, i am here!结果
hello ------------------------------ world, i am here!使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
结果
['hello world,\n', 'i am here!\n'] <class 'list'>小说《Walden》单词词频统计 Walden中文译名《瓦尔登湖》,是美国作家梭罗独居瓦尔登湖畔的记录,描绘了他两年多时间里的所见、所闻和所思。该书崇尚简朴生活,热爱大自然的风光,内容丰厚,意义深远,语言生动。请用Python统计小说Walden中各单词出现的频次,并按频次由高到低排序。 示例: lyric = ‘The night begin to shine, the night begin to shine’ words = lyric.split() print(words) words.count(words[1])
import re # 正则表达式 f = open('Walden.txt', 'r') txt = f.read() # 读取进来的数据类型是字符串 f.close() txt = txt.lower() # 英文字母全部变成小写 txt = re.sub('[,.?:"\'!-]', '', txt) # 去除小说中的标点符号 words = txt.split() # 单词分割 word_sq = {} for i in words: if i not in word_sq.keys(): word_sq[i] = 1 else: word_sq[i] += 1 res = sorted(word_sq.items(), key=lambda x:x[1], reverse=True) # 排序 print(res)txt = re.sub('[,.?:"\'!-]', '', txt) txt = re.sub('带去除的内容', '需替换的内容',需处理的字符串) res = sorted(word_sq.items(), key=lambda x:x[1], reverse=True) reverse是降序排列
结果太长了,自己运行
附 'Walden.txt', 字数限制,需要的私聊我
