国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3處理文件中每個詞的方法

2020-01-04 18:10:32
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了Python3處理文件中每個詞的方法,可實現逐個處理文件中每個詞的功能,需要的朋友可以參考下

本文實例講述了Python3處理文件中每個詞的方法。分享給大家供大家參考。具體實現方法如下:

 

 
  1. '''''''  
  2. Created on Dec 21, 2012  
  3. 處理文件中的每個詞  
  4. @author: liury_lab  
  5. ''' 
  6. import codecs  
  7. the_file = codecs.open('d:/text.txt''rU''UTF-8')  
  8. for line in the_file:  
  9. for word in line.split():  
  10. print(word, end = "|")  
  11. the_file.close()  
  12. # 若詞的定義有變,可使用正則表達式  
  13. # 如詞被定義為數字字母,連字符或單引號構成的序列  
  14. import re  
  15. the_file = codecs.open('d:/text.txt''rU''UTF-8')  
  16. print()  
  17. print('************************************************************************')  
  18. re_word = re.compile('[/w/'-]+')  
  19. for line in the_file:  
  20. for word in re_word.finditer(line):  
  21. print(word.group(0), end = "|")  
  22. the_file.close()  
  23. # 封裝成迭代器  
  24. def words_of_file(file_path, line_to_words = str.split):  
  25. the_file = codecs.open('d:/text.txt''rU''UTF-8')  
  26. for line in the_file:  
  27. for word in line_to_words(line):  
  28. yield word  
  29. the_file.close()  
  30. print()  
  31. print('************************************************************************')  
  32. for word in words_of_file('d:/text.txt'):  
  33. print(word, end = '|')  
  34. def words_by_re(file_path, repattern = '[/w/'-]+'):  
  35. the_file = codecs.open('d:/text.txt''rU''UTF-8')  
  36. re_word = re.compile('[/w/'-]+')  
  37.  
  38. def line_to_words(line):  
  39. for mo in re_word.finditer(line):  
  40. yield mo.group(0# 原書為return,發現結果不對,改為yield  
  41. return words_of_file(file_path, line_to_words)  
  42. print()  
  43. print('************************************************************************')  
  44. for word in words_by_re('d:/text.txt'):  
  45. print(word, end = '|'

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新安县| 闵行区| 浦东新区| 黄骅市| 金华市| 长阳| 武平县| 徐汇区| 宕昌县| 秦安县| 保亭| 昆山市| 项城市| 晴隆县| 谢通门县| 高台县| 广饶县| 辰溪县| 淮滨县| 通州区| 大名县| 桃江县| 阿拉善右旗| 玉田县| 淮滨县| 麦盖提县| 金湖县| 茌平县| 揭西县| 镇平县| 石渠县| 灵石县| 嘉义市| 蓬安县| 佛坪县| 盐池县| 满城县| 仁化县| 湟源县| 长泰县| 遂宁市|