1.python文件读取
#文件操作
f=open('Walden.txt','r') #以只读的方式打开
#txt=f.read() #读取文件内容
txt_lines=f.readlines() #读取文件内容 读取所有行,按行读取,每读完一行就换行'\n'
#txt_100=f.read(100) #加参数,读取前100个字符
#不能同时用多种读取方式,要把其他的注释掉
f.close() #关闭文件
#print(txt) #读进的结果是字符串
print(txt_lines) #读进的结果是列表
#print(txt_100)
2.练习:统计小说中的单词频次
re.sub()函数用来进行字符的替换
def sub(pattern, repl, string, count=0, flags=0)
pattern 是需要替换的内容
repl 是需要替换成的内容
string 对哪一个字符串操作
#练习:统计小说中的单词频次
import re #re是正则表达式中的模块
f=open('Walden.txt','r')
txt=f.read()
f.close()
txt=txt.lower()
txt=re.sub('[,.?:!"\'-]','',txt) #re.sub()函数用来进行字符的替换 去除小说中的标点符号,破折号-一定要写在后面,替换成空,不是空格
#数据预处理完成
words=txt.split() #单词的分割(一定先做数据预处理),分割成列表
print(words)
#开始统计词频
word_sq={} #初始词频
for i in words:
if i not in word_sq.keys():
word_sq[i]=1
else:
word_sq[i]+=1
a=sorted(word_sq.items(),key=lambda x:x[1],reverse=True) #将字典中的元素进行排序 word_sq.items()将字典中的所有键值对取出来
# reverse表示按降序排列
print(word_sq)
print(txt)
print(a)