【发布时间】:2015-03-30 04:22:52
【问题描述】:
我有以下问题。 我有一个读取 .txt 文件并将其转换为字符串的函数。但是,这样做我会丢失文件的所有段落。 例如,如果我的 .txt 文件包含以下内容:
Hello everyone I have a problem with reading a file and turning it into a string.
This is a new paragraph, however it is lost once converted to a string.
And this is another paragraph as well.
现在在阅读了这个 .txt 文件后,我得到了以下字符串:
Hello everyone I have a problem with reading a file and turning it into a string.This is a new paragraph, however it is lost once converted to a string.And this is another paragraph as well.
表示所有段落都消失了。
现在我读取这个文件的命令是:
data = iom.read_file_contents(sys.argv[1])
而 read_file_contents 是以下名为 iom 的模块中的一个函数:
import io
def read_file_contents(name):
return open(name).read()
def write_file_contents(name, text):
with io.open(name, 'w', encoding='utf-8') as outfile: #creates .txt file
outfile.write(unicode(text))
任何帮助将不胜感激。 请求后,我的完整代码如下:
data = iom.read_file_contents(sys.argv[1])
for i in data:
if i not in string.ascii_letters and i not in n and i not in string.punctuation and i !=' ': #removes all non ascii, numbers, punctuation and ' ' characters
data = data.replace(i,"")
iom.write_file_contents(sys.argv[1],data) #rewrites the input .txt file by erasing all non ascii, numbers, punctuation and ' ' characters
output = sub.substitute(data, rotation)
iom.write_file_contents(sys.argv[2], output)
意思是我读取一个文件,我通过删除所有“奇怪”字符(如 φ)来重写它,然后调用替换函数,输入一个字符串和一个将字母映射到其他字母的字典(对输入进行加密):
def substitute(str, cipher): #substitution cipher, takes a string (which will be substituted) and a dictionary
result = ""
n = '0123456789'
for c in str:
if c in string.uppercase or c in string.lowercase:
result = result + cipher[c]
elif c==' ' or c in n or c in string.punctuation:
result = result + c
return result
然后将替代函数的输出写入一个新的 .txt 文件。
【问题讨论】:
-
在打印或写入文件之前,您还对
data进行了哪些其他操作?我敢打赌问题正在那里发生。请提供一个完整的代码示例来演示您的问题。 -
我无法观察到这种行为。你能提供一个reproducible example 吗?顺便说一句,
open(name).read()可能是一种反模式,因为它依赖于 GC“关闭”文件:仅适用于 CPython 等引用计数实现。还是我错了? -
看起来你是
.strip()ping 代码中的某处你没有向我们展示的地方。