python 统计文件中的字符串数目示例

作者:huaibei_北 时间:2022-05-14 11:29:34 

题目:

一个txt文件中已知数据格式为:

C4D
C4D/maya
C4D
C4D/su
C4D/max/AE

统计每个字段出现的次数,比如C4D、maya

先读取文件,将文件中的数据抽取出来:


def getWords(filepath):
 file = open(filepath)
 wordOne=[]
 while(file):
   line = file.readline()
   word = line.split('/')
   wordOne.extend(word)
   if(not line):      #若读取结束了
     break
 wordtwo=[]
 for i in wordOne:
   wordtwo.extend(i.split())
 return wordtwo

说明:这个有一个要注意的地方是文件是被”\n”,”/”两种格式分割而来的,因此需要split两次。

然后定义一个dict,遍历数据,代码如下所示:


def getWordNum(words):
 dictWord={}
 for i in words:
   if(i not in dictWord):
     dictWord[i]=0
   dictWord[i]+=1
 return dictWord

主函数的调用:


filepath='data/new.txt'
words = getWords(filepath)
dictword = getWordNum(words)
print(dictword)

结果:


{'C4D': 9, 'max': 1, 'su': 1, 'maya': 1, 'AE': 3}

说明:

1,


print(type(word))
print(type(splitData[0]))

输出为:


<class 'list'>
<class 'str'>


就是当splitData.extend()执行之后就将原本是list类型的数据转换成str类型的存储起来。只有对str类型的数据才能用split函数

2,


import os
print(os.getcwd())

这个可以输出当前所在位置,对于读取文件很有用。

在读入文件并对文件进行切分的时候,若是含有的切分词太多,那么使用re.split()方法是最方便的,如下所示:


filepath='data/new.txt'
file = open(filepath)    #读取文件
wordOne=[]
symbol = '\n/'       #定义分隔符
symbol = "["+symbol+"]"   #拼接正则表达式
while(file):
 line = file.readline()
 word = re.split(symbol,line)
 wordOne.extend(word)
 if(not line):
   break
#通过上式得到的list中会含有很多的空字符串,所以要去空
wordOne = [x for x in wordOne if x]

来源:https://blog.csdn.net/w417950004/article/details/78424366

标签:python,统计,字符串,数目
0
投稿

猜你喜欢

  • 从8个方面优化ASP代码

    2007-09-16 18:01:00
  • Python Pillow(PIL)库的用法详解

    2022-01-31 13:43:26
  • Python-Selenium自动化爬虫

    2021-04-04 10:55:39
  • Python使用turtle库绘制小猪佩奇(实例代码)

    2021-09-21 08:45:30
  • python Yaml、Json、Dict之间的转化

    2022-05-15 02:26:17
  • Pandas实现dataframe和np.array的相互转换

    2023-05-07 12:33:50
  • javascript设计模式交流(一)Singleton Pattern

    2007-11-29 13:20:00
  • 微信小程序之多文件下载的简单封装示例

    2023-10-19 21:10:06
  • 如何用Pytorch搭建一个房价预测模型

    2022-12-16 17:09:21
  • 在ASP中用“正则表达式对象”来校验数据的合法性

    2010-05-27 12:25:00
  • 一文详解如何实现PyTorch模型编译

    2023-06-03 02:46:27
  • 使用Python将xmind脑图转成excel用例的实现代码(一)

    2021-11-10 12:35:42
  • Python深入浅出分析元类

    2022-01-10 09:09:00
  • php中正则替换函数ereg_replace用法实例

    2023-06-13 03:03:51
  • css样式表滤镜全接触

    2007-10-26 12:48:00
  • python中函数默认值使用注意点详解

    2021-01-26 12:36:44
  • Magic Photo Frame 神奇创意相框

    2009-09-15 20:45:00
  • 详解Python中的时间格式的读取与转换(time模块)

    2021-01-09 17:02:38
  • Python warning警告出现的原因及忽略方法

    2021-10-16 10:59:02
  • Python文件处理

    2022-08-08 10:22:01
  • asp之家 网络编程 m.aspxhome.com