jython 中的数据提取和操作

发布于 2024-08-15 01:36:50 字数 214 浏览 2 评论 0原文

对于给定的文件

,例如:11,345,sdfsfsfs,1232,

我需要从文件中读取上述记录,读取 11 来分隔符并去除空格并存储在另一个文件中,类似地 345 来分隔符去除空格并存储在文件中。这样我需要对多行进行操作。

所以最后在另一个文件中数据应该看起来像

11,345,sdfsfsfs,1232

请建议我方法。感谢您的帮助。

For a given file

For ex : 11 ,345 , sdfsfsfs , 1232

i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do for multiple rows.

so finally in the other file the data should look like

11,345,sdfsfsfs,1232

Please suggest me the way. Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

久光 2024-08-22 01:36:50

打开输入文件(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 的人)。

Open the input file (1) and the output file (2) for reading and writing respectively.

file1 = open('file1', 'r')
file2 = open('file2', 'w')

Iterate over the input file, getting each line. Split the line on a comma. Then re-join the line using a comma, but first stripping the whitespace (using a list comprehension).

for line in file1:
   fields = line.split(',')
   line = ",".join([s.strip() for s in fields])
   file2.write(line + "\n")

Finally, close the input and output files.

file1.close()
file2.close()

I'm not sure of jython's capabilities when it comes to generators, so that is why I used a list comprehension. Please feel free to edit this (someone who knows jython better).

少女净妖师 2024-08-22 01:36:50

您可以采取的一种方法是使用 字符串删除所有空格。翻译函数

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()

One approach you could take would be to remove all whitespace using the string.translate function.

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文