- Python - 文字處理
- Python - 文字處理簡介
- Python - 文字處理環境
- Python - 字串不可變性
- Python - 排序行
- Python - 重新格式化段落
- Python - 統計段落中的標記
- Python - 二進位制 ASCII 轉換
- Python - 字串作為檔案
- Python - 反向讀取檔案
- Python - 過濾重複的單詞
- Python - 從文字中提取電子郵件
- Python - 從文字中提取 URL
- Python - 美化列印
- Python - 文字處理狀態機
- Python - 大寫字母和轉換
- Python - 符號化
- Python - 移除停用詞
- Python - 同義詞和反義詞
- Python - 文字翻譯
- Python - 單詞替換
- Python - 拼寫檢查
- Python - WordNet 介面
- Python - 語料訪問
- Python - 標記單詞
- Python - 塊和縫隙
- Python - 塊分類
- Python - 文字分類
- Python - 二元組
- Python - 處理 PDF
- Python - 處理 Word 文件
- Python - 讀取 RSS 提要
- Python - 情緒分析
- Python - 搜尋和匹配
- Python - 文字處理
- Python - 文字換行
- Python - 頻率分佈
- Python - 文字摘要
- Python - 詞幹演算法
- Python - 約束搜尋
Python - 字串作為檔案
在讀取檔案時,它作為具有多個元素的字典進行讀取。因此,我們可以使用元素的索引來訪問檔案的每一行。在下面的示例中,我們有一個具有多行的檔案,這些行成為檔案的各個元素。
with open ("Path\GodFather.txt", "r") as BigFile:
data=BigFile.readlines()
# Print each line
for i in range(len(data)):
print "Line No- ",i
print data[i]
當我們執行上述程式時,我們會得到以下輸出 -
Line No- 0 Vito Corleone is the aging don (head) of the Corleone Mafia Family. Line No- 1 His youngest son Michael has returned from WWII just in time to see the wedding of Connie Corleone (Michael's sister) to Carlo Rizzi. Line No- 2 All of Michael's family is involved with the Mafia, but Michael just wants to live a normal life. Drug dealer Virgil Sollozzo is looking for Mafia families to offer him protection in exchange for a profit of the drug money. Line No- 3 He approaches Don Corleone about it, but, much against the advice of the Don's lawyer Tom Hagen, the Don is morally against the use of drugs, and turns down the offer. Line No- 4 This does not please Sollozzo, who has the Don shot down by some of his hit men. Line No- 5 The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.
檔案作為字串
但是,整個檔案內容可以作為一個字串讀取,方法是刪除換行符並使用如下所示的 read 函式。在結果中沒有多行。
with open("Path\GodFather.txt", 'r') as BigFile:
data=BigFile.read().replace('\n', '')
# Verify the string type
print type(data)
# Print the file content
print data
當我們執行上述程式時,我們會得到以下輸出 -
Vito Corleone is the aging don (head) of the Corleone Mafia Family. His youngest son Michael has returned from WWII just in time to see the wedding of Connie Corleone (Michael's sister) to Carlo Rizzi. All of Michael's family is involved with the Mafia, but Michael just wants to live a normal life. Drug dealer Virgil Sollozzo is looking for Mafia families to offer him protection in exchange for a profit of the drug money. He approaches Don Corleone about it, but, much against the advice of the Don's lawyer Tom Hagen, the Don is morally against the use of drugs, and turns down the offer.This does not please Sollozzo, who has the Don shot down by some of his hit men. The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.
廣告