python - 创建多行输出文件 (Python)

标签 python text

我有一个包含我想要提取的特定数据的文件。

文件看起来像这样:

DS User ID 1  
random garbage  
random garbage  
DS  N user name 1   
random garbage  
DS User ID 2   
random garbage  
random garbage  
DS  N user name 2

到目前为止我有:

import sys  
import re  
f = open(sys.argv[1])

strToSearch = ""

for line in f:
        strToSearch += line

patFinder1 = re.compile('DS\s+\d{4}|DS\s{2}\w\s{2}\w.*|DS\s{2}N', re.MULTILINE)

for i in findPat1:  
    print(i)

我在屏幕上的输出是这样的:

DS user ID 1  
DS  N user name 1  
DS user ID 2  
DS  N user name 2   

如果我使用以下方式写入文件:

outfile = "test.dat"   
FILE = open(outfile,"a")  
FILE.writelines(line)  
FILE.close()  

所有内容都被推送到一行:

DS user ID 1DS  N user name 1DS user ID 2DS  N user name 2 

我可以接受输出的第一个场景。理想情况下,我想从输出文件中删除“DS”和“DS N”并将其以逗号分隔。

User ID 1,user name 1  
User ID 2, username 2

关于如何实现这一点有什么想法吗?

最佳答案

如果不了解实际的输入数据格式、允许的灵 active 以及解析后的数据将如何使用,就很难提供可靠的解决方案。

仅从上面给出的示例输入/输出,就可以快速编写出一个有效的示例代码:

out = open("test.dat", "a") # output file

for line in open("input.dat"):
    if line[:3] != "DS ": continue # skip "random garbage"

    keys = line.split()[1:] # split, remove "DS"
    if keys[0] != "N": # found ID, print with comma
        out.write(" ".join(keys) + ",")
    else: # found name, print and end line
        out.write(" ".join(keys[1:]) + "\n")

输出文件将是:

User ID 1,user name 1
User ID 2,user name 2

如果格式规范已知,当然可以使用正则表达式使此代码更加健壮。例如:

import re
pat_id = re.compile(r"DS\s+(User ID\s+\d+)")
pat_name = re.compile(r"DS\s+N\s+(.+\s+\d+)")
out = open("test.dat", "a")

for line in open("input.dat"):
    match = pat_id.match(line)
    if match: # found ID, print with comma
        out.write(match.group(1) + ",")
        continue
    match = pat_name.match(line)
    if match: # found name, print and end line
        out.write(match.group(1) + "\n")

上面的两个例子都假设“用户 ID X”总是出现在“N 用户名 X”之前,因此相应的尾随字符是“,”和“\n”。

如果顺序不明确,可以使用数字 ID 作为键将值存储在字典中,然后在解析所有输入后打印出 ID/名称对。

如果您提供更多信息,也许我们可以提供更多帮助。

关于python - 创建多行输出文件 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154913/

相关文章:

python - 如何通过任务名称对 Celery 任务进行速率限制?

python - 从 pandas 数据框中绘制线条

python - 如何在 Python 中静态(词法)绑定(bind)名称?

python - 方法将变量返回到其原始参数变量中

Python Mechanize 登录网站

html - 如何只更改正文

javascript - 如何从字符串中删除某些 html 标签?

python - 计算每个标记在 DataFrame 的每行中出现的次数

powershell - 使用 PowerShell 在长文本文件的顶部插入一行文本

MySQL - 删除列时行大小太大错误