繁体   English   中英

Python 3:有没有更好的方法来查找和替换文本文件中的某些项目?

[英]Python 3: Is there a better way to find and replace certain items in a text file?

我有数千个文本文件,每个文件中有两行文本,请参阅附图。 在此处输入图片说明 我不需要对第一行进行任何更改。 我需要找到并替换第二行中的一些项目,然后以与原始文件完全相同的格式(每行和项目的位置)写入文件。 例如,要将位于第二行末尾的“50.0”更改为“90.0”,我执行了以下操作。

    import 0s, glob
    folder path = "./data/"
    
    for filename in glob.glob(os.path.join(folder_path, '*.ops')):
        with open(filename,'r+') as f:
           existing_lines = f.read().splitlines()
           existing_lines[1]='  1  1     2011   10    1             80.0   50.0   50.0   20.0   
 20.0   90.0'
        with open(filename,'r+') as f:
           f.write ('\n'.join(existing_lines))

有没有解决这个问题的可靠方法?

选择:

import os,glob
import re
folder_path = "./data/"

def listToString(s): 
    empty_str = " " 
    return (empty_str.join(s))
         
for filename in glob.glob(os.path.join(folder_path, '*.ops')):
    with open(filename,'r+') as f:
        list_of_lists = [(re.split(r'(\s+)', (line.strip()))) for line in f]
        list1 = list_of_lists[0]
        list2 = list_of_lists[1]
        list2[-1]= '90.0'
        f.truncate(0)
    
    with open(filename,'r+') as f:
        f.write (listToString(list1)+'\n')
        f.write (listToString(list2))
    

找到一些文本模式的最佳解决方案是使用正则表达式。

正则表达式示例:

import re
line = '  1  1     2011   10    1             80.0   50.0   50.0   20.0   20.0   90.0'
if re.search('( +\d+){5}( +\d+.\d+){6}', line):
    print("This line match to searching pattern")
else:
    print("This line dont mach to pattern")

当你找到感兴趣的线条时,你可以轻松地操纵它们

附言。 如果这不起作用,您必须将 reqluar 表达式'( *\\d+){5}( +\\d+.\\d+){6}'所有空格替换为\\t (这是制表符符号)

你的情况:

import re, os

import 0s, glob
path = "./data/"

for filename in glob.glob(os.path.join(folder_path, '*.ops')):
    edited_lines = ''
    with open(filename, 'r+') as f:
        for line in f.readlines():
            if re.search('( *\d+){5}( +\d+.\d+){6}', line):
                # Here you can modify numeric data whatever you want
            else:
                edited_lines += line
    with open(filename, 'w') as f:
        f.write(edited_lines)

不知道你还想做什么,但现在代码看起来更干净了;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM