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设计】。

相关文章

Python实现保证只能运行一个脚本实例

保证只能运行一个脚本实例,方法是程序运行时监听一个特定端口,如果失败则说明已经有实例在跑。 使用装饰器实现,便于重用 复制代码 代码如下: import functools def ju...

讲解Python中运算符使用时的优先级

讲解Python中运算符使用时的优先级

 运算符优先级来确定条件的表达式中的分组。这会影响一个表达式如何计算。某些运算符的优先级高于其他;例如,乘法运算符的优先级比加法运算更高。 例如x=7 + 3* 2;这里,x被...

python简单线程和协程学习心得(分享)

python中对线程的支持的确不够,不过据说python有足够完备的异步网络框架模块,希望日后能学习到,这里就简单的对python中的线程做个总结 threading库可用来在单独的线程...

老生常谈Python startswith()函数与endswith函数

函数:startswith() 作用:判断字符串是否以指定字符或子字符串开头 一、函数说明 语法:string.startswith(str, beg=0,end=len(string)...

解决Python的str强转int时遇到的问题

数字字符串前后有空格没事: >>> print(int(" 3 ")) 3 但是下面这种带小数点的情况是不可取的: >>> print(in...