python - 用python分割文件中的文本

标签 python file annotations

我正在编写一个脚本,将文件中的文本拆分为序列并写入新文件,如何拆分这样的内容文件? 我想通过创建新标签将注释从 CASIA 注释转换为标签文本

S1248R05.jpg 157 161 104

S1248R05.jpg 157 161 104

S1248R06.jpg 168 190 106

S1248R06.jpg 168 190 106

S1248R07.jpg 158 183 105

S1248R07.jpg 158 183 105    

输出应该是这样的:

S1248R05.jpg

157 161 104

S1248R05.jpg

157 161 104

S1248R06.jpg

168 190 106

S1248R06.jpg 

168 190 106

S1248R07.jpg 

158 183 105

S1248R07.jpg 

158 183 105

这是我的脚本:

    with open(r"C:\Users\Abdou\Downloads\Compressed\CASIA Iris V3 Interval\CASIAInterval.txt") as f:
        contents = f.read()
        print(contents)
        result = [re.sub(r'([A-Z]+\g)', r'\n\1', contents).lstrip() for line in f]
        print(result)
        file = open("testfile.txt","w") 
        str1= ''.join(str(result))
        file.write(str(str1))

这是我的输出:

    S1240L04.jpg 129 204 97
    S1240L05.jpg 158 154 95
    S1241R01.jpg 168 148 107

最佳答案

使用简单的迭代。

例如:

with open(filename) as infile, open("testfile.txt", "w") as outfile:
    data = []
    for line in infile.readlines():
        line = line.strip().split()
        data.append(line[0]+"\n")
        data.append(" ".join(line[1:])+"\n")
    outfile.writelines(data)

输出:

S1248R05.jpg
157 161 104
S1248R05.jpg
157 161 104
S1248R06.jpg
168 190 106
S1248R06.jpg
168 190 106
S1248R07.jpg
158 183 105
S1248R07.jpg
158 183 105

关于python - 用python分割文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55353103/

相关文章:

java - 有什么方法可以将注释的值传递到 Spring Boot 中的配置吗?

java - @RequestMapping 在渲染方法中带有 2 个参数

python - 通过 python paramiko 使用本地参数在 ssh 连接上执行受限远程脚本

python - 集中跟踪多用户Python应用程序中的用户登录

python - 圆形对象记录了碰撞,但它们没有接触

c++ - C++中的输出文件问题

python - 每当我重新启动系统并启动 GAE Launcher 时,Google App Engine 都会出错

image - 在matlab中重命名图像文件名

file - 复制文件的简单方法

Python:将类型提示与注释一起使用