python 处理文本(.txt文件)

1. 用到知识:

1.1Python 文件读写查找、替换的相关操作,

参考:https://blog.csdn.net/liangrui1988/article/details/49539137

1.2Python 插入内容到指定文件的位置

if pos != -1:  
        content = content[:pos] + content_add + content[pos:]

参考:https://blog.csdn.net/jusulysunbeamy/article/details/51290129

1.3Python 的正则表达

Findall

注意:返回的是匹配的字符串,若没有匹配,返回[],而不是什么也不返回

1.4 Python replace的应用

参考:http://www.runoob.com/python/python-reg-expressions.html

1.5 Python 两个list 组合成字典

keys = ['a', 'b', 'c']

values = [1, 2, 3]

dictionary = dict(zip(keys, values))

print(dictionary)

1.6 根据字典的对应关系,对文本进行替换

a_dict = {'apple':'1','tree':'2','123456':'3'}
input_file = open(r'd:\test_body.txt',"r").read();
for key,value in  a_dict.items():
    input_file=input_file.replace(key,value);

1.7 seek的用法:

seek()方法: 用它设置当前文件读/写指针的偏移。

seek()方法的语法如下:fileObject.seek(offset[, whence])。offset参数指明偏移量,第二个参数指出第一个参数偏移基准是哪里:

offset的取值可为:0,1,2;  0 表示移动到一个绝对位置 (从文件开始算起),1 表示移到一个相对位置 (从当前位置算起), 2 表示对于文件尾的一个相对位置。”

参考:https://blog.csdn.net/liuchunming033/article/details/39376147

1.8 整体代码:

import re
import os
class myMethod(object):
    def __init__(self, file1):
        self.file1 = file1
        self._count = None

    def count_main(self, main_str):
        '''
        搜索文件中指定字符串的个数
        :param file_name: 文件名称  type=str
        :param main_str: 要搜索的目标字段  type=str
        :return:
        '''
        fo = open(self.file1, "r+") 
        # 打开文件,r+:打开一个文件用于读写。文件指针将会放在文件的开头。
        # 参考:http://www.runoob.com/python3/python3-inputoutput.html
        li_list = []
        fo.seek(0, 0) 
        for s in fo.readlines():
            li = re.findall(main_str, s)
            if li != []:
                li_list.append(li)
            else:
                continue
        fo.close()
        return len(li_list)

    def add_str(self, file2, main_str):
        '''

        :param file_name: 原始的文件名  type = str
        :param file_new_name: 新生成的文件名 type = str
        :param main_str: 搜索的字符串
        :return:
        '''
        self._count = self.count_main(main_str)
        fo = open(self.file1, "r+")
        fo.seek(0, 0)
        content = fo.read()
        for i in range(1, self._count // 3 + 1):
            add_list = [' id="apname' + str(i) + '" class="ap"', ' class="outer"', ' class="wifi"']
            for j in range(3):
                pos = content.find("<g>")
                if pos != -1:
                    content = content[:pos + 2] + add_list[j] + content[pos + 2:]
        fo_new = open(file2, "w") 
        # w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被         
        # 删除。如果该文件不存在,创建新文件。
        fo_new.write(content)
        fo_new.close()
        fo.close()
        return file2

def excelColToList1(excel_file):
    # data = xlrd.open_workbook(path + '/' + file_r)
    data = xlrd.open_workbook(excel_file)
    sheet1 = data.sheets()[0]


    nrows = sheet1.nrows
    ncols = sheet1.ncols

    apnames = []
    apInPictureNums= []

    for i in range(2, nrows):
        apname = sheet1.cell(i, 9).value
        apname = apname.strip()
        apnames.append(apname)
        apInPictureNum = sheet1.cell(i, 15).value
        apInPictureNum = apInPictureNum.strip()
        apInPictureNums.append(apInPictureNum)
    new_str = [apnames[i] + '" name="' + apInPictureNums[i] for i in range(len(apnames))]
    dictionary = dict(zip(apInPictureNums, new_str))
    return dictionary

    def replace_str(self, file2, old_str, new_str, new_list_strs):
        '''

        :param file2: 需要替换某些字符串的文本 type=“str”
        :param old_str: 需要被替换的字符串 type = "str" 比如apname
        :param new_str: 将old_str 替换成new_str tupe='str' 比如 h2-1f-ap
        :param new_list_strs: 在AI打点时 的顺序
        :return:
        '''
        fo = open(file2, "r")
        mykeys = []
        myvalues = []
        for i in range(0, self._count // 3):
            mykeys.append(old_str+str(i+1))
            myvalues.append(new_str+str(new_list_strs[i]))
        mydict = dict(zip(mykeys, myvalues))
        content = fo.read()
        for key, value in mydict.items():
            content = content.replace(key, value)
        fo_new = open(self.file1, "w")
        fo_new.write(content)
        fo_new.close()
        fo.close()
        os.remove(file2)
        return self.file1

file1 = "testCopy.txt"
file2 = "testCopy2.txt"
main_str = "<g>"
mytest = myMethod(file1)
file = mytest.add_str(file2, main_str)
old_str = "apname"
new_str = "h2-1f-ap"
new_list_strs = [1,2,3]
mytest.replace_str(file, old_str, new_str, new_list_strs)

 

  • 1
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值