Python3处理文件中每个词的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python3处理文件中每个词的方法。分享给大家供大家参考。具体实现方法如下:

''''' 
Created on Dec 21, 2012 
处理文件中的每个词 
@author: liury_lab 
''' 
import codecs 
the_file = codecs.open('d:/text.txt', 'rU', 'UTF-8') 
for line in the_file: 
  for word in line.split(): 
    print(word, end = "|") 
the_file.close() 
# 若词的定义有变,可使用正则表达式 
# 如词被定义为数字字母,连字符或单引号构成的序列 
import re 
the_file = codecs.open('d:/text.txt', 'rU', 'UTF-8') 
print() 
print('************************************************************************') 
re_word = re.compile('[\w\'-]+') 
for line in the_file: 
  for word in re_word.finditer(line): 
    print(word.group(0), end = "|") 
the_file.close() 
# 封装成迭代器 
def words_of_file(file_path, line_to_words = str.split): 
  the_file = codecs.open('d:/text.txt', 'rU', 'UTF-8') 
  for line in the_file: 
    for word in line_to_words(line): 
      yield word 
  the_file.close() 
print() 
print('************************************************************************') 
for word in words_of_file('d:/text.txt'): 
  print(word, end = '|') 
def words_by_re(file_path, repattern = '[\w\'-]+'): 
  the_file = codecs.open('d:/text.txt', 'rU', 'UTF-8') 
  re_word = re.compile('[\w\'-]+') 
 
  def line_to_words(line): 
    for mo in re_word.finditer(line): 
      yield mo.group(0) # 原书为return,发现结果不对,改为yield 
  return words_of_file(file_path, line_to_words) 
print() 
print('************************************************************************') 
for word in words_by_re('d:/text.txt'): 
  print(word, end = '|')

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python选择排序算法的实现代码

1.算法:对于一组关键字{K1,K2,…,Kn}, 首先从K1,K2,…,Kn中选择最小值,假如它是 Kz,则将Kz与 K1对换;然后从K2,K3,… ,Kn中选择最小值 Kz,再将Kz...

基于TensorFlow常量、序列以及随机值生成实例

TensorFlow 生成 常量、序列和随机值 生成常量 tf.constant()这种形式比较常见,除了这一种生成常量的方式之外,像Numpy一样,TensorFlow也提供了生成...

Python中的zipfile模块使用详解

zip文件格式是通用的文档压缩标准,在ziplib模块中,使用ZipFile类来操作zip文件,下面具体介绍一下: class zipfile.ZipFile(file[, mode[,...

几种实用的pythonic语法实例代码

前言 python 是一门简单而优雅的语言,可能是过于简单了,不用花太多时间学习就能使用,其实 python 里面还有一些很好的特性,能大大简化你代码的逻辑,提高代码的可读性。 所谓Py...

Pyinstaller将py打包成exe的实例

Pyinstaller将py打包成exe的实例

背景:分享python编写的小脚本时,拷贝代码还缺各种环境,使用Pyinstaller将py可以打包成exe,直接运行即可 1、安装pyinstaller运行时所需要的windows拓展...