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程序设计有所帮助。

相关文章

libreoffice python 操作word及excel文档的方法

1、开始、关闭libreoffice服务; 开始之前同步字体文件时间,是因为创建soffice服务时,服务会检查所需加载的文件的时间,如果其认为时间不符,则其可能会重新加载,耗时较长,因...

Python的requests网络编程包使用教程

Python的requests网络编程包使用教程

早就听说requests的库的强大,只是还没有接触,今天接触了一下,发现以前使用urllib,urllib2等方法真是太搓了…… 这里写些简单的使用初步作为一个记录 一、下载 官方项目...

对YOLOv3模型调用时候的python接口详解

对YOLOv3模型调用时候的python接口详解

需要注意的是:更改完源程序.c文件,需要对整个项目重新编译、make install,对已经生成的文件进行更新,类似于之前VS中在一个类中增加新函数重新编译封装dll,而python接口...

python异步编程 使用yield from过程解析

前言 yield from 是 Python3.3 后新加的语言结构。yield from的主要功能是打开双向通道,把最外层的调用方法与最内层的子生成器连接起来。这两者就可以进行发送值和...

python概率计算器实例分析

本文实例讲述了python概率计算器实现方法。分享给大家供大家参考。具体实现方法如下: from random import randrange #randrange form ra...