国产探花免费观看_亚洲丰满少妇自慰呻吟_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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金平| 云安县| 宁蒗| 藁城市| 轮台县| 酉阳| 明溪县| 宕昌县| 馆陶县| 承德县| 通榆县| 杭锦旗| 平武县| 织金县| 郸城县| 张家口市| 崇仁县| 崇信县| 玉环县| 吉木乃县| 安乡县| 安西县| 宁南县| 门源| 永春县| 绥棱县| 墨玉县| 陆河县| 申扎县| 新乡县| 白城市| 新宁县| 宝山区| 靖边县| 郸城县| 新安县| 巴东县| 博白县| 广东省| 右玉县| 历史|