- 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.
广告