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 获取等间隔的数组实例

可以使用numpy中的linspace函数 np.linspace(start, stop, num, endpoint, retstep, dtype) #start和stop为起...

整理Python最基本的操作字典的方法

Python 中的字典是Python中一个键值映射的数据结构,下面介绍一下如何优雅的操作字典. 1.1 创建字典 Python有两种方法可以创建字典,第一种是使用花括号,另一种是使用内建...

python matplotlib拟合直线的实现

python matplotlib拟合直线的实现

这篇文章主要介绍了python matplotlib拟合直线的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 imp...

详解Python字典的操作

详解Python字典的操作

本篇介绍Python字典的常见操作。 修改字典元素,如图。 添加字典元素,如图。 删除字典元素del方法,如图。 删除字典元素clear方法,如图。 len(),keys(),...

对Python 窗体(tkinter)树状数据(Treeview)详解

如下所示: import tkinter from tkinter import ttk #导入内部包 win=tkinter.Tk() tree=ttk.Treeview(wi...