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

yipeiwu_com6年前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格式化输出保留2位小数的实现方法

python格式化输出保留2位小数的实现方法

我是小白就不用多说了,学习python做了个练习题,结果运行了一遍,发现输入金额后得到的有很多位小数, 虽然不知道为什么,但是看得很不舒服, 就想到应该把让小数点后只保留2位数 找到了方...

python连接PostgreSQL数据库的过程详解

1. 常用模块 # 连接数据库 connect()函数创建一个新的数据库连接对话并返回一个新的连接实例对象 PG_CONF_123 = { 'user':'emma', 'p...

用pywin32实现windows模拟鼠标及键盘动作

因为要批量用某软件处理一批eps文件,所以要模拟鼠标及键盘动作,使其能够自动化操作。 复制代码 代码如下:#-*-coding:utf-8-*-import osimport timei...

python利用拉链法实现字典方法示例

python利用拉链法实现字典方法示例

前言 字典也叫散列表,最大的特点是通过key来查找其对应的值其时间复杂度是O(1),下面这篇文章就来给大家介绍介绍python利用拉链法实现字典的方法。 在Python中怎样用列表实现字...

PyQt5 QSerialPort子线程操作的实现

环境: python3.6 pyqt5 只是简单的一个思路,请忽略脆弱的异常防护: # -*- coding: utf-8 -*- import sys from PyQt5....