Jython中的数据提取与处理
给定一个文件
比如说:11,345,sdfsfsfs,1232
我需要从这个文件中提取上面的记录,读取11到分隔符,然后去掉空格,存储到另一个文件里。同样地,345也要读取到分隔符,去掉空格后存到文件里。这样我需要对多行进行处理。
所以最后在另一个文件中,数据应该是这样的:
11,345,sdfsfsfs,1232
请给我一些建议。谢谢你的帮助。
2 个回答
0
你可以尝试一种方法,就是使用 string.translate
函数 来去掉所有的空格。
import string
#makes a 256 character string that will be used in the translate function
trans_table = string.maketrans('', '')
file1 = open('file1', 'r')
file2 = open('file2', 'w')
for line in file1:
file2.write(line.translate(trans_table, string.whitespace) + '\n')
#Or the above could be written as:
# line = line.translate(trans_table, string.whitespace)
# file2.write(line + '\n')
file1.close()
file2.close()
2
首先,打开输入文件(1)和输出文件(2),分别用于读取和写入。
file1 = open('file1', 'r')
file2 = open('file2', 'w')
接下来,逐行读取输入文件的内容。每读取一行,就用逗号把这一行分开。然后再用逗号把这些部分重新连接起来,但在连接之前,要先去掉多余的空格(这可以通过列表推导式来实现)。
for line in file1:
fields = line.split(',')
line = ",".join([s.strip() for s in fields])
file2.write(line + "\n")
最后,记得关闭输入和输出文件。
file1.close()
file2.close()
我不太确定jython在生成器方面的功能,所以我用了列表推导式。如果有人对jython更了解,可以随意修改这个部分。