使用python替换特定行中的字符串 [英] Replace string in a specific line using python

查看:48
本文介绍了使用python替换特定行中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 python 脚本来替换目录中具有特定扩展名 (.seq) 的每个文本文件中的字符串.替换的字符串应该只来自每个文件的第二行,并且输出是一个新的子目录(称为干净),与原始文件的文件名相同,但带有 *.clean 后缀.输出文件包含与原始文件完全相同的文本,但替换了字符串.我需要用 'N' 替换所有这些字符串:'K'、'Y'、'W'、'M'、'R'、'S'.

I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The output file contains exactly the same text as the original, but with the strings replaced. I need to replace all these strings: 'K','Y','W','M','R','S' with 'N'.

这是我在谷歌搜索后想到的.它非常混乱(编程的第二周),它停止将文件复制到干净的目录中而不替换任何内容.我真的很感激任何帮助.

This is what I've come up with after googling. It's very messy (2nd week of programming), and it stops at copying the files into the clean directory without replacing anything. I'd really appreciate any help.

之前谢谢!

import os, shutil

os.mkdir('clean')

for file in os.listdir(os.getcwd()):
    if file.find('.seq') != -1:
        shutil.copy(file, 'clean')

os.chdir('clean')

for subdir, dirs, files in os.walk(os.getcwd()):
    for file in files:
        f = open(file, 'r')
        for line in f.read():
            if line.__contains__('>'): #indicator for the first line. the first line always starts with '>'. It's a FASTA file, if you've worked with dna/protein before.
                pass
            else:
                line.replace('M', 'N')
                line.replace('K', 'N')
                line.replace('Y', 'N')
                line.replace('W', 'N')
                line.replace('R', 'N')
                line.replace('S', 'N')

推荐答案

一些注意事项:

  1. string.replacere.sub 不是就地的,因此您应该将返回值分配回您的变量.
  2. glob.glob 更适合在与定义的模式匹配的目录中查找文件...
  3. 也许您应该在创建目录之前检查该目录是否已经存在(我只是假设这一点,这可能不是您想要的行为)
  4. with 语句负责以安全的方式关闭文件.如果你不想使用它,你必须使用 try finally.
  5. 在您的示例中,您忘记放置后缀 *.clean ;)
  6. 你实际上没有写文件,你可以像我在我的例子中那样做,或者使用 fileinput 模块(直到今天我都不知道)
  1. string.replace and re.sub are not in-place so you should be assigning the return value back to your variable.
  2. glob.glob is better for finding files in a directory matching a defined pattern...
  3. maybe you should be checking if the directory already exists before creating it (I just assumed this, this could not be your desired behavior)
  4. the with statement takes care of closing the file in a safe way. if you don't want to use it you have to use try finally.
  5. in your example you where forgetting to put the sufix *.clean ;)
  6. you where not actually writing the files, you could do it like i did in my example or use fileinput module (which until today i did not know)

这是我的例子:

import re
import os
import glob

source_dir=os.getcwd()
target_dir="clean"
source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]

# check if target directory exists... if not, create it.
if not os.path.exists(target_dir):
    os.makedirs(target_dir)

for source_file in source_files:
   target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")
   with open(source_file,'r') as sfile:
      with open(target_file,'w') as tfile:
         lines = sfile.readlines()
         # do the replacement in the second line.
         # (remember that arrays are zero indexed)
         lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])
         tfile.writelines(lines)

print "DONE"

希望能帮到你.

这篇关于使用python替换特定行中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆