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

相关文章

解决DataFrame排序sort的问题

如下所示: result = result.T.sort(['confidence','support'], ascending = False) 报以下错误: Attribu...

11个Python3字典内置方法大全与示例汇总

11个Python3字典内置方法大全与示例汇总

概述 在绝大部分的开发语言中与实际开发过程中,Dictionary扮演着举足轻重的角色。从我们的数据模型到服务器返回的参数到数据库的应用等等,Dictionary的身影无处不在。 在P...

Python语言实现百度语音识别API的使用实例

未来的一段时间,人工智能在市场上占有很重的位置,Python语言则是研究人工智能的最佳编程语言,下面,就让我们来感受一下它的魅力吧! 百度给的样例程序,不论C还是Java版,都分为met...

Python字典生成式、集合生成式、生成器用法实例分析

本文实例讲述了Python字典生成式、集合生成式、生成器用法。分享给大家供大家参考,具体如下: 字典生成式: 跟列表生成式一样,字典生成式用来快速生成字典,不同的是,字典需要两个值...

Python实现的统计文章单词次数功能示例

本文实例讲述了Python实现的统计文章单词次数功能。分享给大家供大家参考,具体如下: 题目是这样的:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文...