Python3處理文件中每個詞的方法
更新時間:2015年05月22日 12:24:46 作者:皮蛋
這篇文章主要介紹了Python3處理文件中每個詞的方法,可實現(xiàn)逐個處理文件中每個詞的功能,需要的朋友可以參考下
本文實例講述了Python3處理文件中每個詞的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
'''''
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()
# 若詞的定義有變,可使用正則表達式
# 如詞被定義為數(shù)字字母,連字符或單引號構(gòu)成的序列
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,發(fā)現(xiàn)結(jié)果不對,改為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程序設(shè)計有所幫助。
相關(guān)文章
手把手教你jupyter?notebook更換環(huán)境的方法
在日常使用jupyter-notebook時,可能會碰到需要切換不同虛擬環(huán)境的場景,下面這篇文章主要給大家介紹了關(guān)于jupyter?notebook更換環(huán)境的方法,需要的朋友可以參考下2023-05-05
Python apscheduler實現(xiàn)定時任務的方法詳解
apscheduler(Advanced Python Scheduler)是一個用于Python的靈活、強大的定時任務調(diào)度庫,它允許您以各種方式安排函數(shù)或方法的執(zhí)行,下面就跟隨小編一起學習一下它的具體使用吧2023-10-10
Python線性擬合實現(xiàn)函數(shù)與用法示例
這篇文章主要介紹了Python線性擬合實現(xiàn)函數(shù)與用法,結(jié)合實例形式分析了Python使用線性擬合算法與不使用線性擬合算法的相關(guān)算法操作技巧,需要的朋友可以參考下2018-12-12
pytorch中torch.max和Tensor.view函數(shù)用法詳解
今天小編就為大家分享一篇pytorch中torch.max和Tensor.view函數(shù)用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
如何使用 Python 中的功能和庫創(chuàng)建 n-gram
在計算語言學中,n-gram 對于語言處理、上下文和語義分析非常重要,它們是從令牌字符串中相鄰的連續(xù)單詞序列,本文將討論如何使用 Python 中的功能和庫創(chuàng)建 n-gram,感興趣的朋友一起看看吧2023-09-09
淺談flask截獲所有訪問及before/after_request修飾器
這篇文章主要介紹了淺談flask截獲所有訪問及before/after_request修飾器,具有一定借鑒價值,需要的朋友可以參考下2018-01-01

