刚刚在写文章时360浏览器崩溃了,结果内容还是找回来了,感谢博客园的自动保存功能!!!

------------恢复内容开始------------

最近在学习Python,自己写了一个小程序,可以从指定的路径中读取文本文档,并统计其中各单词出现的个数并打印

 import os
#此方法用于创建文件夹及文件
def createFile(fileName,content,filePath=r'd:/PythonExercise/'):
# 创建文件夹
os.mkdir(filePath)
fullPath=filePath+fileName
f=open(fullPath,'w')
f.write(content)
f.close
#将下面一句话写入指定的文件
createFile('test.txt',"Life is short,so let's just enjoying Python!") #此方法用于读取文件并统计词频
def getWordsFrequency(fullFilePath=r'd:/PythonExercise/test.txt'):
f=open(fullFilePath,'r')
# 读取内容,并以空格分隔,split中如果不传参,默认为空格,以下适用于英文
tmp=f.readline().split()
# 以下适用于中文,由于中文汉字之间没有空格,读出来整体会是个str,所以要用list()转换成以单个汉字为内容的list
# tmp=list(f.readline()) f.close()
print(tmp)
#标点符号集
punctuation='''~!@#$%^&*()_+-[]{};:,./?"'''
#如果只是以空格分隔,会得到一些单词和标点的组合,如“if,”not!"之类的,遍历list并将其中含有标点的内容分隔,去掉原内容并将分割后的list加在原list后
for i in tmp:
for p in punctuation:
if p in i:
tmp1=i.split(p)
tmp.remove(i)
tmp.extend(tmp1)
#将空元素''去掉并将原有单词中所有字母转换成小写
for j in tmp:
if j=='':
# print("let's remove null")
tmp.remove(j)
else:
# print("let's get lowers")
tmp[tmp.index(j)]=j.lower()
# tmp.replace(j,j.lower())
#上面的if语句中已经去除过''字符,但不知为什么,最后一个去不掉,因此再去除一遍
while tmp.count('')!=0:
tmp.remove('')
# print(tmp.count(''))
# print('tmp after lower case',tmp)
#将处理后的单词列表去重并转化为tuple,方便后面使用
keys=tuple(set(tmp))
print(keys)
#生成一个和上面keys,即去重后的单词的元组长度相同的list,并先赋初值为0,方便后续统计词频
freq=list(0*i for i in range(len(keys)))
# print(freq)
#从keys中获取单词,并在tmp中统计出现的次数,将次数赋给freq中的元素,由于freq长度和keys一样,所以freq的序号可以和keys一一对应,方便后面组成字典
for words in keys:
freq[keys.index(words)]=tmp.count(words)
# print(freq)
#新建一个字典
freqDict={}
#将keys批量导入成为字典的键
freqDict=dict.fromkeys(keys)
#此时如果打印freqDict可以看到它的值全为None
# print(freqDict)
#将上面和和keys一一对应的freq的值赋给freqDict中对应的键
for words in keys:
# print(freqDict[words])
freqDict[words]=freq[keys.index(words)]
print(freqDict)
return freqDict
运行该函数就可以以字典的形式打印出词频
getWordsFrequency() 以下语句是从上面读出的单词中随机抽10个打印出来
wordSet=list(getWordsFrequency().keys())
#print(wordSet)
import random as r
抽取10个不同的元素,此方法随机数可以去重
randomWords=r.sample(wordSet,10)
用下面三行也可以抽出10个单词,但可能会有重复值
# randomWords=[]
# for i in range(10):
# randomWords.append(r.choice(wordSet))
print(randomWords)

程序输出的结果

(1)从bing.com的国际版随意一条热搜中选取了一段新闻并保存到test.txt中,运行结果如下

{'orbit': 1, 'hanging': 2, 'another': 1, 'pretty': 2, 'planets': 2, 'planet': 2, 'of': 2, 'system': 2, 'a': 4, 'rings': 1, 'two': 1, 'there’s': 1, 'life': 1, 'claim': 1, 'features': 1, 'moons': 3, 'both': 1, 'conditions': 1, 'means': 1, 'survey': 1, 'moon': 3, 'chance': 1, 'possible': 1, 'with': 1, 'our': 2, 'body': 1, 'have': 3, 'cnet': 1, 'is': 1, 'uranus': 1, 'red': 1, 'jupiter': 1, 'could': 2, 'earth’s': 2, 'reports': 1, 'several': 1, 'main': 1, 'be': 1, 'are': 1, 'which': 2, 'that’s': 1, 'fame': 1, 'sky': 1, 'earth': 2, 'gravity': 1, 'while': 1, 'place': 1, 'being': 1, 'call': 1, 'spot': 1, 'famous': 2, 'eyes': 1, 'it’s': 1, 'an': 1, 'for': 4, 'that': 3, 'right?': 1, 'solar': 2, 'distinctive': 1, 'its': 5, 'no': 1, 'orbiting': 1, 'has': 4, 'special': 1, 'mercury': 1, 'astronomers': 1, 'mini': 1, 'wondrous': 1, 'human': 1, 'now': 1, 'catalina': 1, 'asteroid': 1, 'single': 1, 'rock': 1, 'this': 1, 'cool': 1, 'and': 3, 'would': 1, 'all': 1, 'on': 1, 'Tuscon': 1, 'out': 2, 'at': 1, 'to': 2, 'az': 1, 'but,': 1, 'saturn': 1, 'use': 1, 'in': 5, 'it': 2, 'many': 1, 'the': 3, 'make': 1, 'home': 1, 'like': 1, 'perfect': 1, 'only': 1}

['to', 'system', 'reports', 'it', 'would', 'no', 'are', 'pretty', 'all', 'make']

(2)从新浪新闻中选取了一条,把其中第二段并保存到test.txt中,运行结果如下
{'闻': 1, '开': 1, '家': 2, '表': 1, '管': 1, '生': 4, '务': 1, '会': 1, '疫': 1, '系': 1, '物': 3, '非': 1, '了': 1, '院': 1, '以': 1, '法': 1, '日': 1, '施': 2, '格': 1, '工': 1, '最': 1, '控': 2, '取': 1, ',': 3, '措': 1, '布': 1, '严': 2, '新': 1, '保': 1, '厉': 1, '作': 1, '。': 2, '召': 1, '来': 1, '打': 1, '野': 3, '局': 2, '和': 2, '动': 3, '护': 1, '王': 1, '示': 1, '林': 2, '实': 1, '副': 1, '场': 1, '2': 1, '贸': 1, '况': 1, '绍': 1, '长': 1, '维': 1, '情': 2, '司': 2, '坚': 1, '击': 1, '防': 1, '决': 1, '胜': 1, '制': 1, '联': 2, '列': 1, '草': 2, '机': 1, '市': 1, '易': 1, '介': 1, '缔': 1, '的': 1, '植': 1, '发': 2, '国': 3, '7': 1, '为': 1}
<class 'list'>
['严', '联', '的', '2', '动', ',', '和', '院', '物', '施'] (3)将python之道的诗保存到test.txt中,运行结果如下
{"aren't": 1, 'implicit': 1, 'right': 1, 'practicality': 1, 'nested': 1, 'although': 3, 'beautiful': 1, 'break': 1, 'errors': 1, 'of': 3, 'refuse': 1, 'a': 2, 'dense': 1, 'more': 1, 'easy': 1, "you're": 1, 'sparse': 1, 'peters': 1, 'do': 2, 'may': 2, 'explicit': 1, 'implementation': 2, 'often': 1, 'great': 1, 'pass': 1, 'those': 1, 'purity': 1, 'is': 10, 'ambiguity': 1, 'face': 1, 'be': 3, 'by': 1, 'are': 1, 'silently': 1, 'cases': 1, 'bad': 1, 'idea': 3, 'if': 2, "it's": 1, 'not': 1, 'counts': 1, 'zen': 1, 'readability': 1, 'that': 1, 'honking': 1, 'temptation': 1, 'than': 8, 'ugly': 1, 'Dutch': 1, "let's": 1, 'guess': 1, 'namespaces': 1, 'special': 2, 'better': 8, 'now': 1, 'good': 1, 'complicated': 1, 'now.': 1, 'simple': 1, 'complex': 2, 'there': 1, 'python': 1, 'first': 1, 'way': 2, 'and': 1, 'beats': 1, 'hard': 1, 'explicitly': 1, 'silenced': 1, 'at': 1, 'to': 5, 'obvious': 2, 'never': 3, 'tim': 1, 'in': 1, 'one': 3, 'explain': 2, 'unless': 2, 'enough': 1, 'preferably': 1, 'should': 2, 'it': 2, 'the': 6, 'flat': 1, 'rules': 1, 'only': 1}
<class 'list'>
['of', 'honking', 'preferably', 'by', "you're", 'complicated', 'sparse', 'and', 'pass', 'enough']

------------恢复内容结束------------

为了防止链接失效,手动将1、2、3中的三段文本放在下面

1、

Several planets in our solar system are famous for distinctive features. Saturn has its wondrous rings and Jupiter has its famous red spot, while Uranus has its many moons and planets like Mercury have no moons at all. Earth’s main claim to fame is it being the only planet in the solar system with the perfect conditions for human life and a single moon, both of which make it a pretty special place for use to call home. But, there’s a chance that Earth could have another moon hanging out in its orbit for now. CNET reports that Catalina Sky Survey astronomers in Tuscon, AZ has its eyes on an asteroid hanging out in Earth’s gravity. It’s possible that this body of rock could be a mini-moon orbiting our planet, which means Earth would have two moons. That’s pretty cool, right?

2、

国务院联防联控机制27日召开新闻发布会,介绍坚决取缔和严厉打击非法野生动物市场和贸易工作情况。国家林草局野生动植物保护司副司长王维胜表示,疫情发生以来,国家林草局实施了最为严格的野生动物管控系列措施。

3、

The Zen of Python, by Tim Peters  Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

用Python读取一个文本文件并统计词频的更多相关文章

  1. asp.net 读取一个文本文件,并输出到网页显示 通过 一般处理程序实现

    asp.net 读取一个文本文件,并输出到网页显示 通过 一般处理程序实现 用这个可以做模板首页进行输出,也可以自已自定义进行扩展 //得到读取到的文本到string中 string resultTe ...

  2. python读取一个文件的每一行判断是否为素数,并把结果写到另一个文件中

    刚刚学习python的菜鸟,这道题包括:文件的读写,python的参数调用,异常的使用,函数的使用 创建一个文本文件inti_prime.txt 执行命令:python Prime.py init_p ...

  3. python 读取一个文件夹下的所jpg文件保存到txt中

    最近需要使用统计一个目录下的所有文件,使用python比较方便,就整理了一下代码. import os def gci(filepath): files = os.listdir(filepath) ...

  4. Python读取一个目录下的所有文件

    #!/usr/bin/python # -*- coding:utf8 -*- import os allFileNum = 0 def printPath(level, path): global ...

  5. python 读取一个目录下的所有目录和文件

    #!/usr/bin/python # -*- coding:utf8 -*- import os allFileNum = 0 def printPath(level, path): global ...

  6. Java读取一个文本文件拼接成一个字符串(readFileToString)

    import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.I ...

  7. python读取一个英文文件,并记录每个单词出现的次数,降序输出

    对文中出现的句号,逗号和感叹号做了相应的处理 sorted排序函数用法: 按照value值降序排列: sorted(dict.items(),key=lambda k:k[1],reverse=Tru ...

  8. 面试题-python 如何读取一个大于 10G 的txt文件?

    前言 用python 读取一个大于10G 的文件,自己电脑只有8G内存,一运行就报内存溢出:MemoryError python 如何用open函数读取大文件呢? 读取大文件 首先可以自己先制作一个大 ...

  9. Python 读取图像文件的性能对比

    Python 读取图像文件的性能对比 使用 Python 读取一个保存在本地硬盘上的视频文件,视频文件的编码方式是使用的原始的 RGBA 格式写入的,即无压缩的原始视频文件.最开始直接使用 Pytho ...

随机推荐

  1. Matplotlib 图形绘制

    章节 Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Mat ...

  2. GNS3 模拟DHCP之地址请求

    R1: conf t int f0/0 no shutdown ip address dhcp end R2: conf t int f0/0 no shutdown ip add 12.1.1.2 ...

  3. 你必须知道的.Net 8.2.2 本质分析

    1 .Equals  静态方法  Equals 静态方法实现了对两个对象的相等性判别,其在 System.Object 类型中实现过程可以表 示为: public static bool Equals ...

  4. 使用gulp 进行ES6开发

    使用gulp 进行ES6开发 一.新建项目 项目结构如下: /app -- /js -- /css /dist -- /js -- /css -- index.html gulpfile.js 我们的 ...

  5. HTML中用自定义字体实现小图标icon(不是原作, 只是一个研究笔记)

    最近在做一个项目时, 研究了一下新浪微博的前端, 看到首页中那个图标了吗, 以前看到这类效果的第一反应就是用一个gif之类的图标做出来!! 但在研究的过程, 发现了一个小技巧, 注意那个em标签中的文 ...

  6. yolov3输出检测图片位置信息

    前言 我们在进行图片识别后需要进行进一步的处理,该文章会介绍:1.怎样取消lables;2.输出并保存(.txt)标记框的位置信息 一.去掉label 在darknet/src/image.c 收索d ...

  7. Spring boot application.properties和 application.yml 初学者的学习

    来自于java尚硅谷教程 简单的说这两个配置文件更改配置都可以更改默认设置的值比如服务器端口号之类的,只需再文件中设置即可, properties可能是出现的比较早了,如果你不调你的默认编码,中文可能 ...

  8. svn全局设置过滤文件没有作用的解决办法

    svn全局设置过滤文件,网上教程文章很多, 都说了怎么配置,没有强调配置内容的格式 导致用惯了git的人,上手配置后,不起作用. 下面是我的配置内容: .classpath .project .set ...

  9. 九、响应式发:rem和less(适配移动端)

    一.响应式开发 响应式开发优先适配移动端又兼容到pc端 官网:https://less.bootcss.com/usage/ 教程:https://www.w3cschool.cn/less/ rem ...

  10. netty权威指南学习笔记三——TCP粘包/拆包之粘包现象

    TCP是个流协议,流没有一定界限.TCP底层不了解业务,他会根据TCP缓冲区的实际情况进行包划分,在业务上,一个业务完整的包,可能会被TCP底层拆分为多个包进行发送,也可能多个小包组合成一个大的数据包 ...