读取的基本格式(txt)

  1. f=open('Walden.txt','r') #以读的方式打开文件
  2. txt=f.read() #读取文件内容
  3. f.close() #关闭文件
  4. print(txt) #打印

运行结果 Walden

  1. Contents<br /> WALDEN<br /> 1. Economy<br /> 2. Where I Lived, and What I Lived For<br /> 3. Reading<br /> ..............<br /> Walden<br /> from [http://manybooks.net/](http://manybooks.net/)<br />注意:读取进来的数据类型为字符串

简单的数据清洗(大写转小*去标点)

  1. import re
  2. x=open('Walden.txt','r')
  3. txt=x.read()
  4. x.close()
  5. txt=txt.lower()#字符串中大写转小写
  6. txt=re.sub('[,.?+$:"\'\/!0123456789-]','',txt)#去除标点与数字
  7. print(txt)

运行结果 walden

  1. contents<br /> walden<br /> economy<br /> where i lived and what i lived for<br /> reading<br /> ..............<br /> walden<br /> from httpmanybooksnet

简单的数据分析(单词使用频率)

  1. import re
  2. x=open('Walden.txt','r')
  3. txt=x.read()
  4. x.close()
  5. txt=txt.lower()#字符串中大写转小写
  6. txt=re.sub('[,.?+$:"\'\/!0123456789-]','',txt)#去除标点与数字
  7. words=txt.split()#单词分割
  8. word_sq={}
  9. for i in words:
  10. if i not in word_sq.keys():
  11. word_sq[i]=1
  12. else:
  13. word_sq[i]+=1
  14. y=sorted(word_sq.items(),key=lambda x:x[1],reverse=True)#排序
  15. print(y)

运行结果 [(‘the’, 7346), (‘and’, 4602), (‘of’, 3490),
…………………….
…………………….
(‘fulfilled’, 1), (‘httpmanybooksnet’, 1)]