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

yipeiwu_com6年前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 统计文件中的字符串数目示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈Pycharm调用同级目录下的py脚本bug

浅谈Pycharm调用同级目录下的py脚本bug

环境:python3.5,pycharm2017.2.3 目录结构 a.py t=5 b.py from a import t print(t) 平台显示 出现红色波浪线警...

python验证身份证信息实例代码

python验证身份证信息实例代码

identity-card 验证身份证号码的正确性,不能仅仅通过正则表达式来验证,我们都知道我国的身份证一共是18位,由十七位数字本体码和一位校验码组成。 其排列顺序从左至右依次为:六位...

Python编写Windows Service服务程序

Python编写Windows Service服务程序

 如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模...

Pandas 按索引合并数据集的方法

如下所示: import numpy as np import pandas as pd from pandas import Series,DataFrame 一、merge函数...

python多线程http下载实现示例

测试平台 Ubuntu 13.04 X86_64 Python 2.7.4 花了将近两个小时, 问题主要刚开始没有想到传一个文件对象到线程里面去, 导致下载下来的文件和源文件MD5不一样...