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

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 统计文件中的字符串数目示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。