欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-09-07 09:11:27|栏目:Python代码|点击:

题目:

一个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]

上一篇:关于多元线性回归分析――Python&SPSS

栏    目:Python代码

下一篇:python sklearn库实现简单逻辑回归的实例代码

本文标题:python 统计文件中的字符串数目示例

本文地址:http://www.codeinn.net/misctech/173349.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有